index.js 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var jsxRuntime = require('react/jsx-runtime');
  4. var React = require('react');
  5. var create = require('./create-DwAwaNot.js');
  6. var motionDom = require('motion-dom');
  7. var motionUtils = require('motion-utils');
  8. function _interopNamespaceDefault(e) {
  9. var n = Object.create(null);
  10. if (e) {
  11. Object.keys(e).forEach(function (k) {
  12. if (k !== 'default') {
  13. var d = Object.getOwnPropertyDescriptor(e, k);
  14. Object.defineProperty(n, k, d.get ? d : {
  15. enumerable: true,
  16. get: function () { return e[k]; }
  17. });
  18. }
  19. });
  20. }
  21. n.default = e;
  22. return Object.freeze(n);
  23. }
  24. var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
  25. /**
  26. * Measurement functionality has to be within a separate component
  27. * to leverage snapshot lifecycle.
  28. */
  29. class PopChildMeasure extends React__namespace.Component {
  30. getSnapshotBeforeUpdate(prevProps) {
  31. const element = this.props.childRef.current;
  32. if (element && prevProps.isPresent && !this.props.isPresent) {
  33. const parent = element.offsetParent;
  34. const parentWidth = parent instanceof HTMLElement ? parent.offsetWidth || 0 : 0;
  35. const size = this.props.sizeRef.current;
  36. size.height = element.offsetHeight || 0;
  37. size.width = element.offsetWidth || 0;
  38. size.top = element.offsetTop;
  39. size.left = element.offsetLeft;
  40. size.right = parentWidth - size.width - size.left;
  41. }
  42. return null;
  43. }
  44. /**
  45. * Required with getSnapshotBeforeUpdate to stop React complaining.
  46. */
  47. componentDidUpdate() { }
  48. render() {
  49. return this.props.children;
  50. }
  51. }
  52. function PopChild({ children, isPresent, anchorX }) {
  53. const id = React.useId();
  54. const ref = React.useRef(null);
  55. const size = React.useRef({
  56. width: 0,
  57. height: 0,
  58. top: 0,
  59. left: 0,
  60. right: 0,
  61. });
  62. const { nonce } = React.useContext(create.MotionConfigContext);
  63. /**
  64. * We create and inject a style block so we can apply this explicit
  65. * sizing in a non-destructive manner by just deleting the style block.
  66. *
  67. * We can't apply size via render as the measurement happens
  68. * in getSnapshotBeforeUpdate (post-render), likewise if we apply the
  69. * styles directly on the DOM node, we might be overwriting
  70. * styles set via the style prop.
  71. */
  72. React.useInsertionEffect(() => {
  73. const { width, height, top, left, right } = size.current;
  74. if (isPresent || !ref.current || !width || !height)
  75. return;
  76. const x = anchorX === "left" ? `left: ${left}` : `right: ${right}`;
  77. ref.current.dataset.motionPopId = id;
  78. const style = document.createElement("style");
  79. if (nonce)
  80. style.nonce = nonce;
  81. document.head.appendChild(style);
  82. if (style.sheet) {
  83. style.sheet.insertRule(`
  84. [data-motion-pop-id="${id}"] {
  85. position: absolute !important;
  86. width: ${width}px !important;
  87. height: ${height}px !important;
  88. ${x}px !important;
  89. top: ${top}px !important;
  90. }
  91. `);
  92. }
  93. return () => {
  94. document.head.removeChild(style);
  95. };
  96. }, [isPresent]);
  97. return (jsxRuntime.jsx(PopChildMeasure, { isPresent: isPresent, childRef: ref, sizeRef: size, children: React__namespace.cloneElement(children, { ref }) }));
  98. }
  99. const PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode, anchorX, }) => {
  100. const presenceChildren = create.useConstant(newChildrenMap);
  101. const id = React.useId();
  102. const memoizedOnExitComplete = React.useCallback((childId) => {
  103. presenceChildren.set(childId, true);
  104. for (const isComplete of presenceChildren.values()) {
  105. if (!isComplete)
  106. return; // can stop searching when any is incomplete
  107. }
  108. onExitComplete && onExitComplete();
  109. }, [presenceChildren, onExitComplete]);
  110. const context = React.useMemo(() => ({
  111. id,
  112. initial,
  113. isPresent,
  114. custom,
  115. onExitComplete: memoizedOnExitComplete,
  116. register: (childId) => {
  117. presenceChildren.set(childId, false);
  118. return () => presenceChildren.delete(childId);
  119. },
  120. }),
  121. /**
  122. * If the presence of a child affects the layout of the components around it,
  123. * we want to make a new context value to ensure they get re-rendered
  124. * so they can detect that layout change.
  125. */
  126. presenceAffectsLayout
  127. ? [Math.random(), memoizedOnExitComplete]
  128. : [isPresent, memoizedOnExitComplete]);
  129. React.useMemo(() => {
  130. presenceChildren.forEach((_, key) => presenceChildren.set(key, false));
  131. }, [isPresent]);
  132. /**
  133. * If there's no `motion` components to fire exit animations, we want to remove this
  134. * component immediately.
  135. */
  136. React__namespace.useEffect(() => {
  137. !isPresent &&
  138. !presenceChildren.size &&
  139. onExitComplete &&
  140. onExitComplete();
  141. }, [isPresent]);
  142. if (mode === "popLayout") {
  143. children = (jsxRuntime.jsx(PopChild, { isPresent: isPresent, anchorX: anchorX, children: children }));
  144. }
  145. return (jsxRuntime.jsx(create.PresenceContext.Provider, { value: context, children: children }));
  146. };
  147. function newChildrenMap() {
  148. return new Map();
  149. }
  150. const getChildKey = (child) => child.key || "";
  151. function onlyElements(children) {
  152. const filtered = [];
  153. // We use forEach here instead of map as map mutates the component key by preprending `.$`
  154. React.Children.forEach(children, (child) => {
  155. if (React.isValidElement(child))
  156. filtered.push(child);
  157. });
  158. return filtered;
  159. }
  160. /**
  161. * `AnimatePresence` enables the animation of components that have been removed from the tree.
  162. *
  163. * When adding/removing more than a single child, every child **must** be given a unique `key` prop.
  164. *
  165. * Any `motion` components that have an `exit` property defined will animate out when removed from
  166. * the tree.
  167. *
  168. * ```jsx
  169. * import { motion, AnimatePresence } from 'framer-motion'
  170. *
  171. * export const Items = ({ items }) => (
  172. * <AnimatePresence>
  173. * {items.map(item => (
  174. * <motion.div
  175. * key={item.id}
  176. * initial={{ opacity: 0 }}
  177. * animate={{ opacity: 1 }}
  178. * exit={{ opacity: 0 }}
  179. * />
  180. * ))}
  181. * </AnimatePresence>
  182. * )
  183. * ```
  184. *
  185. * You can sequence exit animations throughout a tree using variants.
  186. *
  187. * If a child contains multiple `motion` components with `exit` props, it will only unmount the child
  188. * once all `motion` components have finished animating out. Likewise, any components using
  189. * `usePresence` all need to call `safeToRemove`.
  190. *
  191. * @public
  192. */
  193. const AnimatePresence = ({ children, custom, initial = true, onExitComplete, presenceAffectsLayout = true, mode = "sync", propagate = false, anchorX = "left", }) => {
  194. const [isParentPresent, safeToRemove] = create.usePresence(propagate);
  195. /**
  196. * Filter any children that aren't ReactElements. We can only track components
  197. * between renders with a props.key.
  198. */
  199. const presentChildren = React.useMemo(() => onlyElements(children), [children]);
  200. /**
  201. * Track the keys of the currently rendered children. This is used to
  202. * determine which children are exiting.
  203. */
  204. const presentKeys = propagate && !isParentPresent ? [] : presentChildren.map(getChildKey);
  205. /**
  206. * If `initial={false}` we only want to pass this to components in the first render.
  207. */
  208. const isInitialRender = React.useRef(true);
  209. /**
  210. * A ref containing the currently present children. When all exit animations
  211. * are complete, we use this to re-render the component with the latest children
  212. * *committed* rather than the latest children *rendered*.
  213. */
  214. const pendingPresentChildren = React.useRef(presentChildren);
  215. /**
  216. * Track which exiting children have finished animating out.
  217. */
  218. const exitComplete = create.useConstant(() => new Map());
  219. /**
  220. * Save children to render as React state. To ensure this component is concurrent-safe,
  221. * we check for exiting children via an effect.
  222. */
  223. const [diffedChildren, setDiffedChildren] = React.useState(presentChildren);
  224. const [renderedChildren, setRenderedChildren] = React.useState(presentChildren);
  225. create.useIsomorphicLayoutEffect(() => {
  226. isInitialRender.current = false;
  227. pendingPresentChildren.current = presentChildren;
  228. /**
  229. * Update complete status of exiting children.
  230. */
  231. for (let i = 0; i < renderedChildren.length; i++) {
  232. const key = getChildKey(renderedChildren[i]);
  233. if (!presentKeys.includes(key)) {
  234. if (exitComplete.get(key) !== true) {
  235. exitComplete.set(key, false);
  236. }
  237. }
  238. else {
  239. exitComplete.delete(key);
  240. }
  241. }
  242. }, [renderedChildren, presentKeys.length, presentKeys.join("-")]);
  243. const exitingChildren = [];
  244. if (presentChildren !== diffedChildren) {
  245. let nextChildren = [...presentChildren];
  246. /**
  247. * Loop through all the currently rendered components and decide which
  248. * are exiting.
  249. */
  250. for (let i = 0; i < renderedChildren.length; i++) {
  251. const child = renderedChildren[i];
  252. const key = getChildKey(child);
  253. if (!presentKeys.includes(key)) {
  254. nextChildren.splice(i, 0, child);
  255. exitingChildren.push(child);
  256. }
  257. }
  258. /**
  259. * If we're in "wait" mode, and we have exiting children, we want to
  260. * only render these until they've all exited.
  261. */
  262. if (mode === "wait" && exitingChildren.length) {
  263. nextChildren = exitingChildren;
  264. }
  265. setRenderedChildren(onlyElements(nextChildren));
  266. setDiffedChildren(presentChildren);
  267. /**
  268. * Early return to ensure once we've set state with the latest diffed
  269. * children, we can immediately re-render.
  270. */
  271. return null;
  272. }
  273. if (process.env.NODE_ENV !== "production" &&
  274. mode === "wait" &&
  275. renderedChildren.length > 1) {
  276. console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);
  277. }
  278. /**
  279. * If we've been provided a forceRender function by the LayoutGroupContext,
  280. * we can use it to force a re-render amongst all surrounding components once
  281. * all components have finished animating out.
  282. */
  283. const { forceRender } = React.useContext(create.LayoutGroupContext);
  284. return (jsxRuntime.jsx(jsxRuntime.Fragment, { children: renderedChildren.map((child) => {
  285. const key = getChildKey(child);
  286. const isPresent = propagate && !isParentPresent
  287. ? false
  288. : presentChildren === renderedChildren ||
  289. presentKeys.includes(key);
  290. const onExit = () => {
  291. if (exitComplete.has(key)) {
  292. exitComplete.set(key, true);
  293. }
  294. else {
  295. return;
  296. }
  297. let isEveryExitComplete = true;
  298. exitComplete.forEach((isExitComplete) => {
  299. if (!isExitComplete)
  300. isEveryExitComplete = false;
  301. });
  302. if (isEveryExitComplete) {
  303. forceRender?.();
  304. setRenderedChildren(pendingPresentChildren.current);
  305. propagate && safeToRemove?.();
  306. onExitComplete && onExitComplete();
  307. }
  308. };
  309. return (jsxRuntime.jsx(PresenceChild, { isPresent: isPresent, initial: !isInitialRender.current || initial
  310. ? undefined
  311. : false, custom: custom, presenceAffectsLayout: presenceAffectsLayout, mode: mode, onExitComplete: isPresent ? undefined : onExit, anchorX: anchorX, children: child }, key));
  312. }) }));
  313. };
  314. /**
  315. * Note: Still used by components generated by old versions of Framer
  316. *
  317. * @deprecated
  318. */
  319. const DeprecatedLayoutGroupContext = React.createContext(null);
  320. const notify = (node) => !node.isLayoutDirty && node.willUpdate(false);
  321. function nodeGroup() {
  322. const nodes = new Set();
  323. const subscriptions = new WeakMap();
  324. const dirtyAll = () => nodes.forEach(notify);
  325. return {
  326. add: (node) => {
  327. nodes.add(node);
  328. subscriptions.set(node, node.addEventListener("willUpdate", dirtyAll));
  329. },
  330. remove: (node) => {
  331. nodes.delete(node);
  332. const unsubscribe = subscriptions.get(node);
  333. if (unsubscribe) {
  334. unsubscribe();
  335. subscriptions.delete(node);
  336. }
  337. dirtyAll();
  338. },
  339. dirty: dirtyAll,
  340. };
  341. }
  342. function useIsMounted() {
  343. const isMounted = React.useRef(false);
  344. create.useIsomorphicLayoutEffect(() => {
  345. isMounted.current = true;
  346. return () => {
  347. isMounted.current = false;
  348. };
  349. }, []);
  350. return isMounted;
  351. }
  352. function useForceUpdate() {
  353. const isMounted = useIsMounted();
  354. const [forcedRenderCount, setForcedRenderCount] = React.useState(0);
  355. const forceRender = React.useCallback(() => {
  356. isMounted.current && setForcedRenderCount(forcedRenderCount + 1);
  357. }, [forcedRenderCount]);
  358. /**
  359. * Defer this to the end of the next animation frame in case there are multiple
  360. * synchronous calls.
  361. */
  362. const deferredForceRender = React.useCallback(() => motionDom.frame.postRender(forceRender), [forceRender]);
  363. return [deferredForceRender, forcedRenderCount];
  364. }
  365. const shouldInheritGroup = (inherit) => inherit === true;
  366. const shouldInheritId = (inherit) => shouldInheritGroup(inherit === true) || inherit === "id";
  367. const LayoutGroup = ({ children, id, inherit = true }) => {
  368. const layoutGroupContext = React.useContext(create.LayoutGroupContext);
  369. const deprecatedLayoutGroupContext = React.useContext(DeprecatedLayoutGroupContext);
  370. const [forceRender, key] = useForceUpdate();
  371. const context = React.useRef(null);
  372. const upstreamId = layoutGroupContext.id || deprecatedLayoutGroupContext;
  373. if (context.current === null) {
  374. if (shouldInheritId(inherit) && upstreamId) {
  375. id = id ? upstreamId + "-" + id : upstreamId;
  376. }
  377. context.current = {
  378. id,
  379. group: shouldInheritGroup(inherit)
  380. ? layoutGroupContext.group || nodeGroup()
  381. : nodeGroup(),
  382. };
  383. }
  384. const memoizedContext = React.useMemo(() => ({ ...context.current, forceRender }), [key]);
  385. return (jsxRuntime.jsx(create.LayoutGroupContext.Provider, { value: memoizedContext, children: children }));
  386. };
  387. /**
  388. * Used in conjunction with the `m` component to reduce bundle size.
  389. *
  390. * `m` is a version of the `motion` component that only loads functionality
  391. * critical for the initial render.
  392. *
  393. * `LazyMotion` can then be used to either synchronously or asynchronously
  394. * load animation and gesture support.
  395. *
  396. * ```jsx
  397. * // Synchronous loading
  398. * import { LazyMotion, m, domAnimation } from "framer-motion"
  399. *
  400. * function App() {
  401. * return (
  402. * <LazyMotion features={domAnimation}>
  403. * <m.div animate={{ scale: 2 }} />
  404. * </LazyMotion>
  405. * )
  406. * }
  407. *
  408. * // Asynchronous loading
  409. * import { LazyMotion, m } from "framer-motion"
  410. *
  411. * function App() {
  412. * return (
  413. * <LazyMotion features={() => import('./path/to/domAnimation')}>
  414. * <m.div animate={{ scale: 2 }} />
  415. * </LazyMotion>
  416. * )
  417. * }
  418. * ```
  419. *
  420. * @public
  421. */
  422. function LazyMotion({ children, features, strict = false }) {
  423. const [, setIsLoaded] = React.useState(!isLazyBundle(features));
  424. const loadedRenderer = React.useRef(undefined);
  425. /**
  426. * If this is a synchronous load, load features immediately
  427. */
  428. if (!isLazyBundle(features)) {
  429. const { renderer, ...loadedFeatures } = features;
  430. loadedRenderer.current = renderer;
  431. create.loadFeatures(loadedFeatures);
  432. }
  433. React.useEffect(() => {
  434. if (isLazyBundle(features)) {
  435. features().then(({ renderer, ...loadedFeatures }) => {
  436. create.loadFeatures(loadedFeatures);
  437. loadedRenderer.current = renderer;
  438. setIsLoaded(true);
  439. });
  440. }
  441. }, []);
  442. return (jsxRuntime.jsx(create.LazyContext.Provider, { value: { renderer: loadedRenderer.current, strict }, children: children }));
  443. }
  444. function isLazyBundle(features) {
  445. return typeof features === "function";
  446. }
  447. /**
  448. * `MotionConfig` is used to set configuration options for all children `motion` components.
  449. *
  450. * ```jsx
  451. * import { motion, MotionConfig } from "framer-motion"
  452. *
  453. * export function App() {
  454. * return (
  455. * <MotionConfig transition={{ type: "spring" }}>
  456. * <motion.div animate={{ x: 100 }} />
  457. * </MotionConfig>
  458. * )
  459. * }
  460. * ```
  461. *
  462. * @public
  463. */
  464. function MotionConfig({ children, isValidProp, ...config }) {
  465. isValidProp && create.loadExternalIsValidProp(isValidProp);
  466. /**
  467. * Inherit props from any parent MotionConfig components
  468. */
  469. config = { ...React.useContext(create.MotionConfigContext), ...config };
  470. /**
  471. * Don't allow isStatic to change between renders as it affects how many hooks
  472. * motion components fire.
  473. */
  474. config.isStatic = create.useConstant(() => config.isStatic);
  475. /**
  476. * Creating a new config context object will re-render every `motion` component
  477. * every time it renders. So we only want to create a new one sparingly.
  478. */
  479. const context = React.useMemo(() => config, [
  480. JSON.stringify(config.transition),
  481. config.transformPagePoint,
  482. config.reducedMotion,
  483. ]);
  484. return (jsxRuntime.jsx(create.MotionConfigContext.Provider, { value: context, children: children }));
  485. }
  486. const ReorderContext = React.createContext(null);
  487. function createDOMMotionComponentProxy(componentFactory) {
  488. if (typeof Proxy === "undefined") {
  489. return componentFactory;
  490. }
  491. /**
  492. * A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc.
  493. * Rather than generating them anew every render.
  494. */
  495. const componentCache = new Map();
  496. const deprecatedFactoryFunction = (...args) => {
  497. if (process.env.NODE_ENV !== "production") {
  498. motionUtils.warnOnce(false, "motion() is deprecated. Use motion.create() instead.");
  499. }
  500. return componentFactory(...args);
  501. };
  502. return new Proxy(deprecatedFactoryFunction, {
  503. /**
  504. * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc.
  505. * The prop name is passed through as `key` and we can use that to generate a `motion`
  506. * DOM component with that name.
  507. */
  508. get: (_target, key) => {
  509. if (key === "create")
  510. return componentFactory;
  511. /**
  512. * If this element doesn't exist in the component cache, create it and cache.
  513. */
  514. if (!componentCache.has(key)) {
  515. componentCache.set(key, componentFactory(key));
  516. }
  517. return componentCache.get(key);
  518. },
  519. });
  520. }
  521. const motion = /*@__PURE__*/ createDOMMotionComponentProxy(create.createMotionComponent);
  522. function checkReorder(order, value, offset, velocity) {
  523. if (!velocity)
  524. return order;
  525. const index = order.findIndex((item) => item.value === value);
  526. if (index === -1)
  527. return order;
  528. const nextOffset = velocity > 0 ? 1 : -1;
  529. const nextItem = order[index + nextOffset];
  530. if (!nextItem)
  531. return order;
  532. const item = order[index];
  533. const nextLayout = nextItem.layout;
  534. const nextItemCenter = create.mixNumber(nextLayout.min, nextLayout.max, 0.5);
  535. if ((nextOffset === 1 && item.layout.max + offset > nextItemCenter) ||
  536. (nextOffset === -1 && item.layout.min + offset < nextItemCenter)) {
  537. return motionUtils.moveItem(order, index, index + nextOffset);
  538. }
  539. return order;
  540. }
  541. function ReorderGroupComponent({ children, as = "ul", axis = "y", onReorder, values, ...props }, externalRef) {
  542. const Component = create.useConstant(() => motion[as]);
  543. const order = [];
  544. const isReordering = React.useRef(false);
  545. motionUtils.invariant(Boolean(values), "Reorder.Group must be provided a values prop");
  546. const context = {
  547. axis,
  548. registerItem: (value, layout) => {
  549. // If the entry was already added, update it rather than adding it again
  550. const idx = order.findIndex((entry) => value === entry.value);
  551. if (idx !== -1) {
  552. order[idx].layout = layout[axis];
  553. }
  554. else {
  555. order.push({ value: value, layout: layout[axis] });
  556. }
  557. order.sort(compareMin);
  558. },
  559. updateOrder: (item, offset, velocity) => {
  560. if (isReordering.current)
  561. return;
  562. const newOrder = checkReorder(order, item, offset, velocity);
  563. if (order !== newOrder) {
  564. isReordering.current = true;
  565. onReorder(newOrder
  566. .map(getValue)
  567. .filter((value) => values.indexOf(value) !== -1));
  568. }
  569. },
  570. };
  571. React.useEffect(() => {
  572. isReordering.current = false;
  573. });
  574. return (jsxRuntime.jsx(Component, { ...props, ref: externalRef, ignoreStrict: true, children: jsxRuntime.jsx(ReorderContext.Provider, { value: context, children: children }) }));
  575. }
  576. const ReorderGroup = /*@__PURE__*/ React.forwardRef(ReorderGroupComponent);
  577. function getValue(item) {
  578. return item.value;
  579. }
  580. function compareMin(a, b) {
  581. return a.layout.min - b.layout.min;
  582. }
  583. /**
  584. * Creates a `MotionValue` to track the state and velocity of a value.
  585. *
  586. * Usually, these are created automatically. For advanced use-cases, like use with `useTransform`, you can create `MotionValue`s externally and pass them into the animated component via the `style` prop.
  587. *
  588. * ```jsx
  589. * export const MyComponent = () => {
  590. * const scale = useMotionValue(1)
  591. *
  592. * return <motion.div style={{ scale }} />
  593. * }
  594. * ```
  595. *
  596. * @param initial - The initial state.
  597. *
  598. * @public
  599. */
  600. function useMotionValue(initial) {
  601. const value = create.useConstant(() => motionDom.motionValue(initial));
  602. /**
  603. * If this motion value is being used in static mode, like on
  604. * the Framer canvas, force components to rerender when the motion
  605. * value is updated.
  606. */
  607. const { isStatic } = React.useContext(create.MotionConfigContext);
  608. if (isStatic) {
  609. const [, setLatest] = React.useState(initial);
  610. React.useEffect(() => value.on("change", setLatest), []);
  611. }
  612. return value;
  613. }
  614. const isCustomValueType = (v) => {
  615. return v && typeof v === "object" && v.mix;
  616. };
  617. const getMixer = (v) => (isCustomValueType(v) ? v.mix : undefined);
  618. function transform(...args) {
  619. const useImmediate = !Array.isArray(args[0]);
  620. const argOffset = useImmediate ? 0 : -1;
  621. const inputValue = args[0 + argOffset];
  622. const inputRange = args[1 + argOffset];
  623. const outputRange = args[2 + argOffset];
  624. const options = args[3 + argOffset];
  625. const interpolator = create.interpolate(inputRange, outputRange, {
  626. mixer: getMixer(outputRange[0]),
  627. ...options,
  628. });
  629. return useImmediate ? interpolator(inputValue) : interpolator;
  630. }
  631. function useCombineMotionValues(values, combineValues) {
  632. /**
  633. * Initialise the returned motion value. This remains the same between renders.
  634. */
  635. const value = useMotionValue(combineValues());
  636. /**
  637. * Create a function that will update the template motion value with the latest values.
  638. * This is pre-bound so whenever a motion value updates it can schedule its
  639. * execution in Framesync. If it's already been scheduled it won't be fired twice
  640. * in a single frame.
  641. */
  642. const updateValue = () => value.set(combineValues());
  643. /**
  644. * Synchronously update the motion value with the latest values during the render.
  645. * This ensures that within a React render, the styles applied to the DOM are up-to-date.
  646. */
  647. updateValue();
  648. /**
  649. * Subscribe to all motion values found within the template. Whenever any of them change,
  650. * schedule an update.
  651. */
  652. create.useIsomorphicLayoutEffect(() => {
  653. const scheduleUpdate = () => motionDom.frame.preRender(updateValue, false, true);
  654. const subscriptions = values.map((v) => v.on("change", scheduleUpdate));
  655. return () => {
  656. subscriptions.forEach((unsubscribe) => unsubscribe());
  657. motionDom.cancelFrame(updateValue);
  658. };
  659. });
  660. return value;
  661. }
  662. function useComputed(compute) {
  663. /**
  664. * Open session of collectMotionValues. Any MotionValue that calls get()
  665. * will be saved into this array.
  666. */
  667. motionDom.collectMotionValues.current = [];
  668. compute();
  669. const value = useCombineMotionValues(motionDom.collectMotionValues.current, compute);
  670. /**
  671. * Synchronously close session of collectMotionValues.
  672. */
  673. motionDom.collectMotionValues.current = undefined;
  674. return value;
  675. }
  676. function useTransform(input, inputRangeOrTransformer, outputRange, options) {
  677. if (typeof input === "function") {
  678. return useComputed(input);
  679. }
  680. const transformer = typeof inputRangeOrTransformer === "function"
  681. ? inputRangeOrTransformer
  682. : transform(inputRangeOrTransformer, outputRange, options);
  683. return Array.isArray(input)
  684. ? useListTransform(input, transformer)
  685. : useListTransform([input], ([latest]) => transformer(latest));
  686. }
  687. function useListTransform(values, transformer) {
  688. const latest = create.useConstant(() => []);
  689. return useCombineMotionValues(values, () => {
  690. latest.length = 0;
  691. const numValues = values.length;
  692. for (let i = 0; i < numValues; i++) {
  693. latest[i] = values[i].get();
  694. }
  695. return transformer(latest);
  696. });
  697. }
  698. function useDefaultMotionValue(value, defaultValue = 0) {
  699. return create.isMotionValue(value) ? value : useMotionValue(defaultValue);
  700. }
  701. function ReorderItemComponent({ children, style = {}, value, as = "li", onDrag, layout = true, ...props }, externalRef) {
  702. const Component = create.useConstant(() => motion[as]);
  703. const context = React.useContext(ReorderContext);
  704. const point = {
  705. x: useDefaultMotionValue(style.x),
  706. y: useDefaultMotionValue(style.y),
  707. };
  708. const zIndex = useTransform([point.x, point.y], ([latestX, latestY]) => latestX || latestY ? 1 : "unset");
  709. motionUtils.invariant(Boolean(context), "Reorder.Item must be a child of Reorder.Group");
  710. const { axis, registerItem, updateOrder } = context;
  711. return (jsxRuntime.jsx(Component, { drag: axis, ...props, dragSnapToOrigin: true, style: { ...style, x: point.x, y: point.y, zIndex }, layout: layout, onDrag: (event, gesturePoint) => {
  712. const { velocity } = gesturePoint;
  713. velocity[axis] &&
  714. updateOrder(value, point[axis].get(), velocity[axis]);
  715. onDrag && onDrag(event, gesturePoint);
  716. }, onLayoutMeasure: (measured) => registerItem(value, measured), ref: externalRef, ignoreStrict: true, children: children }));
  717. }
  718. const ReorderItem = /*@__PURE__*/ React.forwardRef(ReorderItemComponent);
  719. var namespace = /*#__PURE__*/Object.freeze({
  720. __proto__: null,
  721. Group: ReorderGroup,
  722. Item: ReorderItem
  723. });
  724. const wrap = (min, max, v) => {
  725. const rangeSize = max - min;
  726. return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;
  727. };
  728. function getEasingForSegment(easing, i) {
  729. return create.isEasingArray(easing) ? easing[wrap(0, easing.length, i)] : easing;
  730. }
  731. function isDOMKeyframes(keyframes) {
  732. return typeof keyframes === "object" && !Array.isArray(keyframes);
  733. }
  734. function resolveSubjects(subject, keyframes, scope, selectorCache) {
  735. if (typeof subject === "string" && isDOMKeyframes(keyframes)) {
  736. return motionDom.resolveElements(subject, scope, selectorCache);
  737. }
  738. else if (subject instanceof NodeList) {
  739. return Array.from(subject);
  740. }
  741. else if (Array.isArray(subject)) {
  742. return subject;
  743. }
  744. else {
  745. return [subject];
  746. }
  747. }
  748. function calculateRepeatDuration(duration, repeat, _repeatDelay) {
  749. return duration * (repeat + 1);
  750. }
  751. /**
  752. * Given a absolute or relative time definition and current/prev time state of the sequence,
  753. * calculate an absolute time for the next keyframes.
  754. */
  755. function calcNextTime(current, next, prev, labels) {
  756. if (typeof next === "number") {
  757. return next;
  758. }
  759. else if (next.startsWith("-") || next.startsWith("+")) {
  760. return Math.max(0, current + parseFloat(next));
  761. }
  762. else if (next === "<") {
  763. return prev;
  764. }
  765. else {
  766. return labels.get(next) ?? current;
  767. }
  768. }
  769. function eraseKeyframes(sequence, startTime, endTime) {
  770. for (let i = 0; i < sequence.length; i++) {
  771. const keyframe = sequence[i];
  772. if (keyframe.at > startTime && keyframe.at < endTime) {
  773. motionUtils.removeItem(sequence, keyframe);
  774. // If we remove this item we have to push the pointer back one
  775. i--;
  776. }
  777. }
  778. }
  779. function addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) {
  780. /**
  781. * Erase every existing value between currentTime and targetTime,
  782. * this will essentially splice this timeline into any currently
  783. * defined ones.
  784. */
  785. eraseKeyframes(sequence, startTime, endTime);
  786. for (let i = 0; i < keyframes.length; i++) {
  787. sequence.push({
  788. value: keyframes[i],
  789. at: create.mixNumber(startTime, endTime, offset[i]),
  790. easing: getEasingForSegment(easing, i),
  791. });
  792. }
  793. }
  794. /**
  795. * Take an array of times that represent repeated keyframes. For instance
  796. * if we have original times of [0, 0.5, 1] then our repeated times will
  797. * be [0, 0.5, 1, 1, 1.5, 2]. Loop over the times and scale them back
  798. * down to a 0-1 scale.
  799. */
  800. function normalizeTimes(times, repeat) {
  801. for (let i = 0; i < times.length; i++) {
  802. times[i] = times[i] / (repeat + 1);
  803. }
  804. }
  805. function compareByTime(a, b) {
  806. if (a.at === b.at) {
  807. if (a.value === null)
  808. return 1;
  809. if (b.value === null)
  810. return -1;
  811. return 0;
  812. }
  813. else {
  814. return a.at - b.at;
  815. }
  816. }
  817. const defaultSegmentEasing = "easeInOut";
  818. const MAX_REPEAT = 20;
  819. function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...sequenceTransition } = {}, scope, generators) {
  820. const defaultDuration = defaultTransition.duration || 0.3;
  821. const animationDefinitions = new Map();
  822. const sequences = new Map();
  823. const elementCache = {};
  824. const timeLabels = new Map();
  825. let prevTime = 0;
  826. let currentTime = 0;
  827. let totalDuration = 0;
  828. /**
  829. * Build the timeline by mapping over the sequence array and converting
  830. * the definitions into keyframes and offsets with absolute time values.
  831. * These will later get converted into relative offsets in a second pass.
  832. */
  833. for (let i = 0; i < sequence.length; i++) {
  834. const segment = sequence[i];
  835. /**
  836. * If this is a timeline label, mark it and skip the rest of this iteration.
  837. */
  838. if (typeof segment === "string") {
  839. timeLabels.set(segment, currentTime);
  840. continue;
  841. }
  842. else if (!Array.isArray(segment)) {
  843. timeLabels.set(segment.name, calcNextTime(currentTime, segment.at, prevTime, timeLabels));
  844. continue;
  845. }
  846. let [subject, keyframes, transition = {}] = segment;
  847. /**
  848. * If a relative or absolute time value has been specified we need to resolve
  849. * it in relation to the currentTime.
  850. */
  851. if (transition.at !== undefined) {
  852. currentTime = calcNextTime(currentTime, transition.at, prevTime, timeLabels);
  853. }
  854. /**
  855. * Keep track of the maximum duration in this definition. This will be
  856. * applied to currentTime once the definition has been parsed.
  857. */
  858. let maxDuration = 0;
  859. const resolveValueSequence = (valueKeyframes, valueTransition, valueSequence, elementIndex = 0, numSubjects = 0) => {
  860. const valueKeyframesAsList = keyframesAsList(valueKeyframes);
  861. const { delay = 0, times = create.defaultOffset(valueKeyframesAsList), type = "keyframes", repeat, repeatType, repeatDelay = 0, ...remainingTransition } = valueTransition;
  862. let { ease = defaultTransition.ease || "easeOut", duration } = valueTransition;
  863. /**
  864. * Resolve stagger() if defined.
  865. */
  866. const calculatedDelay = typeof delay === "function"
  867. ? delay(elementIndex, numSubjects)
  868. : delay;
  869. /**
  870. * If this animation should and can use a spring, generate a spring easing function.
  871. */
  872. const numKeyframes = valueKeyframesAsList.length;
  873. const createGenerator = motionDom.isGenerator(type)
  874. ? type
  875. : generators?.[type];
  876. if (numKeyframes <= 2 && createGenerator) {
  877. /**
  878. * As we're creating an easing function from a spring,
  879. * ideally we want to generate it using the real distance
  880. * between the two keyframes. However this isn't always
  881. * possible - in these situations we use 0-100.
  882. */
  883. let absoluteDelta = 100;
  884. if (numKeyframes === 2 &&
  885. isNumberKeyframesArray(valueKeyframesAsList)) {
  886. const delta = valueKeyframesAsList[1] - valueKeyframesAsList[0];
  887. absoluteDelta = Math.abs(delta);
  888. }
  889. const springTransition = { ...remainingTransition };
  890. if (duration !== undefined) {
  891. springTransition.duration = motionUtils.secondsToMilliseconds(duration);
  892. }
  893. const springEasing = motionDom.createGeneratorEasing(springTransition, absoluteDelta, createGenerator);
  894. ease = springEasing.ease;
  895. duration = springEasing.duration;
  896. }
  897. duration ?? (duration = defaultDuration);
  898. const startTime = currentTime + calculatedDelay;
  899. /**
  900. * If there's only one time offset of 0, fill in a second with length 1
  901. */
  902. if (times.length === 1 && times[0] === 0) {
  903. times[1] = 1;
  904. }
  905. /**
  906. * Fill out if offset if fewer offsets than keyframes
  907. */
  908. const remainder = times.length - valueKeyframesAsList.length;
  909. remainder > 0 && create.fillOffset(times, remainder);
  910. /**
  911. * If only one value has been set, ie [1], push a null to the start of
  912. * the keyframe array. This will let us mark a keyframe at this point
  913. * that will later be hydrated with the previous value.
  914. */
  915. valueKeyframesAsList.length === 1 &&
  916. valueKeyframesAsList.unshift(null);
  917. /**
  918. * Handle repeat options
  919. */
  920. if (repeat) {
  921. motionUtils.invariant(repeat < MAX_REPEAT, "Repeat count too high, must be less than 20");
  922. duration = calculateRepeatDuration(duration, repeat);
  923. const originalKeyframes = [...valueKeyframesAsList];
  924. const originalTimes = [...times];
  925. ease = Array.isArray(ease) ? [...ease] : [ease];
  926. const originalEase = [...ease];
  927. for (let repeatIndex = 0; repeatIndex < repeat; repeatIndex++) {
  928. valueKeyframesAsList.push(...originalKeyframes);
  929. for (let keyframeIndex = 0; keyframeIndex < originalKeyframes.length; keyframeIndex++) {
  930. times.push(originalTimes[keyframeIndex] + (repeatIndex + 1));
  931. ease.push(keyframeIndex === 0
  932. ? "linear"
  933. : getEasingForSegment(originalEase, keyframeIndex - 1));
  934. }
  935. }
  936. normalizeTimes(times, repeat);
  937. }
  938. const targetTime = startTime + duration;
  939. /**
  940. * Add keyframes, mapping offsets to absolute time.
  941. */
  942. addKeyframes(valueSequence, valueKeyframesAsList, ease, times, startTime, targetTime);
  943. maxDuration = Math.max(calculatedDelay + duration, maxDuration);
  944. totalDuration = Math.max(targetTime, totalDuration);
  945. };
  946. if (create.isMotionValue(subject)) {
  947. const subjectSequence = getSubjectSequence(subject, sequences);
  948. resolveValueSequence(keyframes, transition, getValueSequence("default", subjectSequence));
  949. }
  950. else {
  951. const subjects = resolveSubjects(subject, keyframes, scope, elementCache);
  952. const numSubjects = subjects.length;
  953. /**
  954. * For every element in this segment, process the defined values.
  955. */
  956. for (let subjectIndex = 0; subjectIndex < numSubjects; subjectIndex++) {
  957. /**
  958. * Cast necessary, but we know these are of this type
  959. */
  960. keyframes = keyframes;
  961. transition = transition;
  962. const thisSubject = subjects[subjectIndex];
  963. const subjectSequence = getSubjectSequence(thisSubject, sequences);
  964. for (const key in keyframes) {
  965. resolveValueSequence(keyframes[key], getValueTransition(transition, key), getValueSequence(key, subjectSequence), subjectIndex, numSubjects);
  966. }
  967. }
  968. }
  969. prevTime = currentTime;
  970. currentTime += maxDuration;
  971. }
  972. /**
  973. * For every element and value combination create a new animation.
  974. */
  975. sequences.forEach((valueSequences, element) => {
  976. for (const key in valueSequences) {
  977. const valueSequence = valueSequences[key];
  978. /**
  979. * Arrange all the keyframes in ascending time order.
  980. */
  981. valueSequence.sort(compareByTime);
  982. const keyframes = [];
  983. const valueOffset = [];
  984. const valueEasing = [];
  985. /**
  986. * For each keyframe, translate absolute times into
  987. * relative offsets based on the total duration of the timeline.
  988. */
  989. for (let i = 0; i < valueSequence.length; i++) {
  990. const { at, value, easing } = valueSequence[i];
  991. keyframes.push(value);
  992. valueOffset.push(motionUtils.progress(0, totalDuration, at));
  993. valueEasing.push(easing || "easeOut");
  994. }
  995. /**
  996. * If the first keyframe doesn't land on offset: 0
  997. * provide one by duplicating the initial keyframe. This ensures
  998. * it snaps to the first keyframe when the animation starts.
  999. */
  1000. if (valueOffset[0] !== 0) {
  1001. valueOffset.unshift(0);
  1002. keyframes.unshift(keyframes[0]);
  1003. valueEasing.unshift(defaultSegmentEasing);
  1004. }
  1005. /**
  1006. * If the last keyframe doesn't land on offset: 1
  1007. * provide one with a null wildcard value. This will ensure it
  1008. * stays static until the end of the animation.
  1009. */
  1010. if (valueOffset[valueOffset.length - 1] !== 1) {
  1011. valueOffset.push(1);
  1012. keyframes.push(null);
  1013. }
  1014. if (!animationDefinitions.has(element)) {
  1015. animationDefinitions.set(element, {
  1016. keyframes: {},
  1017. transition: {},
  1018. });
  1019. }
  1020. const definition = animationDefinitions.get(element);
  1021. definition.keyframes[key] = keyframes;
  1022. definition.transition[key] = {
  1023. ...defaultTransition,
  1024. duration: totalDuration,
  1025. ease: valueEasing,
  1026. times: valueOffset,
  1027. ...sequenceTransition,
  1028. };
  1029. }
  1030. });
  1031. return animationDefinitions;
  1032. }
  1033. function getSubjectSequence(subject, sequences) {
  1034. !sequences.has(subject) && sequences.set(subject, {});
  1035. return sequences.get(subject);
  1036. }
  1037. function getValueSequence(name, sequences) {
  1038. if (!sequences[name])
  1039. sequences[name] = [];
  1040. return sequences[name];
  1041. }
  1042. function keyframesAsList(keyframes) {
  1043. return Array.isArray(keyframes) ? keyframes : [keyframes];
  1044. }
  1045. function getValueTransition(transition, key) {
  1046. return transition && transition[key]
  1047. ? {
  1048. ...transition,
  1049. ...transition[key],
  1050. }
  1051. : { ...transition };
  1052. }
  1053. const isNumber = (keyframe) => typeof keyframe === "number";
  1054. const isNumberKeyframesArray = (keyframes) => keyframes.every(isNumber);
  1055. function isObjectKey(key, object) {
  1056. return key in object;
  1057. }
  1058. class ObjectVisualElement extends create.VisualElement {
  1059. constructor() {
  1060. super(...arguments);
  1061. this.type = "object";
  1062. }
  1063. readValueFromInstance(instance, key) {
  1064. if (isObjectKey(key, instance)) {
  1065. const value = instance[key];
  1066. if (typeof value === "string" || typeof value === "number") {
  1067. return value;
  1068. }
  1069. }
  1070. return undefined;
  1071. }
  1072. getBaseTargetFromProps() {
  1073. return undefined;
  1074. }
  1075. removeValueFromRenderState(key, renderState) {
  1076. delete renderState.output[key];
  1077. }
  1078. measureInstanceViewportBox() {
  1079. return create.createBox();
  1080. }
  1081. build(renderState, latestValues) {
  1082. Object.assign(renderState.output, latestValues);
  1083. }
  1084. renderInstance(instance, { output }) {
  1085. Object.assign(instance, output);
  1086. }
  1087. sortInstanceNodePosition() {
  1088. return 0;
  1089. }
  1090. }
  1091. function createDOMVisualElement(element) {
  1092. const options = {
  1093. presenceContext: null,
  1094. props: {},
  1095. visualState: {
  1096. renderState: {
  1097. transform: {},
  1098. transformOrigin: {},
  1099. style: {},
  1100. vars: {},
  1101. attrs: {},
  1102. },
  1103. latestValues: {},
  1104. },
  1105. };
  1106. const node = create.isSVGElement(element)
  1107. ? new create.SVGVisualElement(options)
  1108. : new create.HTMLVisualElement(options);
  1109. node.mount(element);
  1110. create.visualElementStore.set(element, node);
  1111. }
  1112. function createObjectVisualElement(subject) {
  1113. const options = {
  1114. presenceContext: null,
  1115. props: {},
  1116. visualState: {
  1117. renderState: {
  1118. output: {},
  1119. },
  1120. latestValues: {},
  1121. },
  1122. };
  1123. const node = new ObjectVisualElement(options);
  1124. node.mount(subject);
  1125. create.visualElementStore.set(subject, node);
  1126. }
  1127. function isSingleValue(subject, keyframes) {
  1128. return (create.isMotionValue(subject) ||
  1129. typeof subject === "number" ||
  1130. (typeof subject === "string" && !isDOMKeyframes(keyframes)));
  1131. }
  1132. /**
  1133. * Implementation
  1134. */
  1135. function animateSubject(subject, keyframes, options, scope) {
  1136. const animations = [];
  1137. if (isSingleValue(subject, keyframes)) {
  1138. animations.push(create.animateSingleValue(subject, isDOMKeyframes(keyframes)
  1139. ? keyframes.default || keyframes
  1140. : keyframes, options ? options.default || options : options));
  1141. }
  1142. else {
  1143. const subjects = resolveSubjects(subject, keyframes, scope);
  1144. const numSubjects = subjects.length;
  1145. motionUtils.invariant(Boolean(numSubjects), "No valid elements provided.");
  1146. for (let i = 0; i < numSubjects; i++) {
  1147. const thisSubject = subjects[i];
  1148. const createVisualElement = thisSubject instanceof Element
  1149. ? createDOMVisualElement
  1150. : createObjectVisualElement;
  1151. if (!create.visualElementStore.has(thisSubject)) {
  1152. createVisualElement(thisSubject);
  1153. }
  1154. const visualElement = create.visualElementStore.get(thisSubject);
  1155. const transition = { ...options };
  1156. /**
  1157. * Resolve stagger function if provided.
  1158. */
  1159. if ("delay" in transition &&
  1160. typeof transition.delay === "function") {
  1161. transition.delay = transition.delay(i, numSubjects);
  1162. }
  1163. animations.push(...create.animateTarget(visualElement, { ...keyframes, transition }, {}));
  1164. }
  1165. }
  1166. return animations;
  1167. }
  1168. function animateSequence(sequence, options, scope) {
  1169. const animations = [];
  1170. const animationDefinitions = createAnimationsFromSequence(sequence, options, scope, { spring: create.spring });
  1171. animationDefinitions.forEach(({ keyframes, transition }, subject) => {
  1172. animations.push(...animateSubject(subject, keyframes, transition));
  1173. });
  1174. return animations;
  1175. }
  1176. function isSequence(value) {
  1177. return Array.isArray(value) && value.some(Array.isArray);
  1178. }
  1179. /**
  1180. * Creates an animation function that is optionally scoped
  1181. * to a specific element.
  1182. */
  1183. function createScopedAnimate(scope) {
  1184. /**
  1185. * Implementation
  1186. */
  1187. function scopedAnimate(subjectOrSequence, optionsOrKeyframes, options) {
  1188. let animations = [];
  1189. if (isSequence(subjectOrSequence)) {
  1190. animations = animateSequence(subjectOrSequence, optionsOrKeyframes, scope);
  1191. }
  1192. else {
  1193. animations = animateSubject(subjectOrSequence, optionsOrKeyframes, options, scope);
  1194. }
  1195. const animation = new motionDom.GroupAnimationWithThen(animations);
  1196. if (scope) {
  1197. scope.animations.push(animation);
  1198. }
  1199. return animation;
  1200. }
  1201. return scopedAnimate;
  1202. }
  1203. const animate = createScopedAnimate();
  1204. function animateElements(elementOrSelector, keyframes, options, scope) {
  1205. const elements = motionDom.resolveElements(elementOrSelector, scope);
  1206. const numElements = elements.length;
  1207. motionUtils.invariant(Boolean(numElements), "No valid element provided.");
  1208. const animations = [];
  1209. for (let i = 0; i < numElements; i++) {
  1210. const element = elements[i];
  1211. const elementTransition = { ...options };
  1212. /**
  1213. * Resolve stagger function if provided.
  1214. */
  1215. if (typeof elementTransition.delay === "function") {
  1216. elementTransition.delay = elementTransition.delay(i, numElements);
  1217. }
  1218. for (const valueName in keyframes) {
  1219. const valueKeyframes = keyframes[valueName];
  1220. const valueOptions = {
  1221. ...motionDom.getValueTransition(elementTransition, valueName),
  1222. };
  1223. valueOptions.duration && (valueOptions.duration = motionUtils.secondsToMilliseconds(valueOptions.duration));
  1224. valueOptions.delay && (valueOptions.delay = motionUtils.secondsToMilliseconds(valueOptions.delay));
  1225. animations.push(new motionDom.NativeAnimation({
  1226. element,
  1227. name: valueName,
  1228. keyframes: valueKeyframes,
  1229. transition: valueOptions,
  1230. allowFlatten: !elementTransition.type && !elementTransition.ease,
  1231. }));
  1232. }
  1233. }
  1234. return animations;
  1235. }
  1236. const createScopedWaapiAnimate = (scope) => {
  1237. function scopedAnimate(elementOrSelector, keyframes, options) {
  1238. return new motionDom.GroupAnimationWithThen(animateElements(elementOrSelector, keyframes, options, scope));
  1239. }
  1240. return scopedAnimate;
  1241. };
  1242. const animateMini = /*@__PURE__*/ createScopedWaapiAnimate();
  1243. function observeTimeline(update, timeline) {
  1244. let prevProgress;
  1245. const onFrame = () => {
  1246. const { currentTime } = timeline;
  1247. const percentage = currentTime === null ? 0 : currentTime.value;
  1248. const progress = percentage / 100;
  1249. if (prevProgress !== progress) {
  1250. update(progress);
  1251. }
  1252. prevProgress = progress;
  1253. };
  1254. motionDom.frame.update(onFrame, true);
  1255. return () => motionDom.cancelFrame(onFrame);
  1256. }
  1257. const resizeHandlers = new WeakMap();
  1258. let observer;
  1259. function getElementSize(target, borderBoxSize) {
  1260. if (borderBoxSize) {
  1261. const { inlineSize, blockSize } = borderBoxSize[0];
  1262. return { width: inlineSize, height: blockSize };
  1263. }
  1264. else if (target instanceof SVGElement && "getBBox" in target) {
  1265. return target.getBBox();
  1266. }
  1267. else {
  1268. return {
  1269. width: target.offsetWidth,
  1270. height: target.offsetHeight,
  1271. };
  1272. }
  1273. }
  1274. function notifyTarget({ target, contentRect, borderBoxSize, }) {
  1275. resizeHandlers.get(target)?.forEach((handler) => {
  1276. handler({
  1277. target,
  1278. contentSize: contentRect,
  1279. get size() {
  1280. return getElementSize(target, borderBoxSize);
  1281. },
  1282. });
  1283. });
  1284. }
  1285. function notifyAll(entries) {
  1286. entries.forEach(notifyTarget);
  1287. }
  1288. function createResizeObserver() {
  1289. if (typeof ResizeObserver === "undefined")
  1290. return;
  1291. observer = new ResizeObserver(notifyAll);
  1292. }
  1293. function resizeElement(target, handler) {
  1294. if (!observer)
  1295. createResizeObserver();
  1296. const elements = motionDom.resolveElements(target);
  1297. elements.forEach((element) => {
  1298. let elementHandlers = resizeHandlers.get(element);
  1299. if (!elementHandlers) {
  1300. elementHandlers = new Set();
  1301. resizeHandlers.set(element, elementHandlers);
  1302. }
  1303. elementHandlers.add(handler);
  1304. observer?.observe(element);
  1305. });
  1306. return () => {
  1307. elements.forEach((element) => {
  1308. const elementHandlers = resizeHandlers.get(element);
  1309. elementHandlers?.delete(handler);
  1310. if (!elementHandlers?.size) {
  1311. observer?.unobserve(element);
  1312. }
  1313. });
  1314. };
  1315. }
  1316. const windowCallbacks = new Set();
  1317. let windowResizeHandler;
  1318. function createWindowResizeHandler() {
  1319. windowResizeHandler = () => {
  1320. const size = {
  1321. width: window.innerWidth,
  1322. height: window.innerHeight,
  1323. };
  1324. const info = {
  1325. target: window,
  1326. size,
  1327. contentSize: size,
  1328. };
  1329. windowCallbacks.forEach((callback) => callback(info));
  1330. };
  1331. window.addEventListener("resize", windowResizeHandler);
  1332. }
  1333. function resizeWindow(callback) {
  1334. windowCallbacks.add(callback);
  1335. if (!windowResizeHandler)
  1336. createWindowResizeHandler();
  1337. return () => {
  1338. windowCallbacks.delete(callback);
  1339. if (!windowCallbacks.size && windowResizeHandler) {
  1340. windowResizeHandler = undefined;
  1341. }
  1342. };
  1343. }
  1344. function resize(a, b) {
  1345. return typeof a === "function" ? resizeWindow(a) : resizeElement(a, b);
  1346. }
  1347. /**
  1348. * A time in milliseconds, beyond which we consider the scroll velocity to be 0.
  1349. */
  1350. const maxElapsed = 50;
  1351. const createAxisInfo = () => ({
  1352. current: 0,
  1353. offset: [],
  1354. progress: 0,
  1355. scrollLength: 0,
  1356. targetOffset: 0,
  1357. targetLength: 0,
  1358. containerLength: 0,
  1359. velocity: 0,
  1360. });
  1361. const createScrollInfo = () => ({
  1362. time: 0,
  1363. x: createAxisInfo(),
  1364. y: createAxisInfo(),
  1365. });
  1366. const keys = {
  1367. x: {
  1368. length: "Width",
  1369. position: "Left",
  1370. },
  1371. y: {
  1372. length: "Height",
  1373. position: "Top",
  1374. },
  1375. };
  1376. function updateAxisInfo(element, axisName, info, time) {
  1377. const axis = info[axisName];
  1378. const { length, position } = keys[axisName];
  1379. const prev = axis.current;
  1380. const prevTime = info.time;
  1381. axis.current = element[`scroll${position}`];
  1382. axis.scrollLength = element[`scroll${length}`] - element[`client${length}`];
  1383. axis.offset.length = 0;
  1384. axis.offset[0] = 0;
  1385. axis.offset[1] = axis.scrollLength;
  1386. axis.progress = motionUtils.progress(0, axis.scrollLength, axis.current);
  1387. const elapsed = time - prevTime;
  1388. axis.velocity =
  1389. elapsed > maxElapsed
  1390. ? 0
  1391. : motionUtils.velocityPerSecond(axis.current - prev, elapsed);
  1392. }
  1393. function updateScrollInfo(element, info, time) {
  1394. updateAxisInfo(element, "x", info, time);
  1395. updateAxisInfo(element, "y", info, time);
  1396. info.time = time;
  1397. }
  1398. function calcInset(element, container) {
  1399. const inset = { x: 0, y: 0 };
  1400. let current = element;
  1401. while (current && current !== container) {
  1402. if (current instanceof HTMLElement) {
  1403. inset.x += current.offsetLeft;
  1404. inset.y += current.offsetTop;
  1405. current = current.offsetParent;
  1406. }
  1407. else if (current.tagName === "svg") {
  1408. /**
  1409. * This isn't an ideal approach to measuring the offset of <svg /> tags.
  1410. * It would be preferable, given they behave like HTMLElements in most ways
  1411. * to use offsetLeft/Top. But these don't exist on <svg />. Likewise we
  1412. * can't use .getBBox() like most SVG elements as these provide the offset
  1413. * relative to the SVG itself, which for <svg /> is usually 0x0.
  1414. */
  1415. const svgBoundingBox = current.getBoundingClientRect();
  1416. current = current.parentElement;
  1417. const parentBoundingBox = current.getBoundingClientRect();
  1418. inset.x += svgBoundingBox.left - parentBoundingBox.left;
  1419. inset.y += svgBoundingBox.top - parentBoundingBox.top;
  1420. }
  1421. else if (current instanceof SVGGraphicsElement) {
  1422. const { x, y } = current.getBBox();
  1423. inset.x += x;
  1424. inset.y += y;
  1425. let svg = null;
  1426. let parent = current.parentNode;
  1427. while (!svg) {
  1428. if (parent.tagName === "svg") {
  1429. svg = parent;
  1430. }
  1431. parent = current.parentNode;
  1432. }
  1433. current = svg;
  1434. }
  1435. else {
  1436. break;
  1437. }
  1438. }
  1439. return inset;
  1440. }
  1441. const namedEdges = {
  1442. start: 0,
  1443. center: 0.5,
  1444. end: 1,
  1445. };
  1446. function resolveEdge(edge, length, inset = 0) {
  1447. let delta = 0;
  1448. /**
  1449. * If we have this edge defined as a preset, replace the definition
  1450. * with the numerical value.
  1451. */
  1452. if (edge in namedEdges) {
  1453. edge = namedEdges[edge];
  1454. }
  1455. /**
  1456. * Handle unit values
  1457. */
  1458. if (typeof edge === "string") {
  1459. const asNumber = parseFloat(edge);
  1460. if (edge.endsWith("px")) {
  1461. delta = asNumber;
  1462. }
  1463. else if (edge.endsWith("%")) {
  1464. edge = asNumber / 100;
  1465. }
  1466. else if (edge.endsWith("vw")) {
  1467. delta = (asNumber / 100) * document.documentElement.clientWidth;
  1468. }
  1469. else if (edge.endsWith("vh")) {
  1470. delta = (asNumber / 100) * document.documentElement.clientHeight;
  1471. }
  1472. else {
  1473. edge = asNumber;
  1474. }
  1475. }
  1476. /**
  1477. * If the edge is defined as a number, handle as a progress value.
  1478. */
  1479. if (typeof edge === "number") {
  1480. delta = length * edge;
  1481. }
  1482. return inset + delta;
  1483. }
  1484. const defaultOffset = [0, 0];
  1485. function resolveOffset(offset, containerLength, targetLength, targetInset) {
  1486. let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset;
  1487. let targetPoint = 0;
  1488. let containerPoint = 0;
  1489. if (typeof offset === "number") {
  1490. /**
  1491. * If we're provided offset: [0, 0.5, 1] then each number x should become
  1492. * [x, x], so we default to the behaviour of mapping 0 => 0 of both target
  1493. * and container etc.
  1494. */
  1495. offsetDefinition = [offset, offset];
  1496. }
  1497. else if (typeof offset === "string") {
  1498. offset = offset.trim();
  1499. if (offset.includes(" ")) {
  1500. offsetDefinition = offset.split(" ");
  1501. }
  1502. else {
  1503. /**
  1504. * If we're provided a definition like "100px" then we want to apply
  1505. * that only to the top of the target point, leaving the container at 0.
  1506. * Whereas a named offset like "end" should be applied to both.
  1507. */
  1508. offsetDefinition = [offset, namedEdges[offset] ? offset : `0`];
  1509. }
  1510. }
  1511. targetPoint = resolveEdge(offsetDefinition[0], targetLength, targetInset);
  1512. containerPoint = resolveEdge(offsetDefinition[1], containerLength);
  1513. return targetPoint - containerPoint;
  1514. }
  1515. const ScrollOffset = {
  1516. Enter: [
  1517. [0, 1],
  1518. [1, 1],
  1519. ],
  1520. Exit: [
  1521. [0, 0],
  1522. [1, 0],
  1523. ],
  1524. Any: [
  1525. [1, 0],
  1526. [0, 1],
  1527. ],
  1528. All: [
  1529. [0, 0],
  1530. [1, 1],
  1531. ],
  1532. };
  1533. const point = { x: 0, y: 0 };
  1534. function getTargetSize(target) {
  1535. return "getBBox" in target && target.tagName !== "svg"
  1536. ? target.getBBox()
  1537. : { width: target.clientWidth, height: target.clientHeight };
  1538. }
  1539. function resolveOffsets(container, info, options) {
  1540. const { offset: offsetDefinition = ScrollOffset.All } = options;
  1541. const { target = container, axis = "y" } = options;
  1542. const lengthLabel = axis === "y" ? "height" : "width";
  1543. const inset = target !== container ? calcInset(target, container) : point;
  1544. /**
  1545. * Measure the target and container. If they're the same thing then we
  1546. * use the container's scrollWidth/Height as the target, from there
  1547. * all other calculations can remain the same.
  1548. */
  1549. const targetSize = target === container
  1550. ? { width: container.scrollWidth, height: container.scrollHeight }
  1551. : getTargetSize(target);
  1552. const containerSize = {
  1553. width: container.clientWidth,
  1554. height: container.clientHeight,
  1555. };
  1556. /**
  1557. * Reset the length of the resolved offset array rather than creating a new one.
  1558. * TODO: More reusable data structures for targetSize/containerSize would also be good.
  1559. */
  1560. info[axis].offset.length = 0;
  1561. /**
  1562. * Populate the offset array by resolving the user's offset definition into
  1563. * a list of pixel scroll offets.
  1564. */
  1565. let hasChanged = !info[axis].interpolate;
  1566. const numOffsets = offsetDefinition.length;
  1567. for (let i = 0; i < numOffsets; i++) {
  1568. const offset = resolveOffset(offsetDefinition[i], containerSize[lengthLabel], targetSize[lengthLabel], inset[axis]);
  1569. if (!hasChanged && offset !== info[axis].interpolatorOffsets[i]) {
  1570. hasChanged = true;
  1571. }
  1572. info[axis].offset[i] = offset;
  1573. }
  1574. /**
  1575. * If the pixel scroll offsets have changed, create a new interpolator function
  1576. * to map scroll value into a progress.
  1577. */
  1578. if (hasChanged) {
  1579. info[axis].interpolate = create.interpolate(info[axis].offset, create.defaultOffset(offsetDefinition), { clamp: false });
  1580. info[axis].interpolatorOffsets = [...info[axis].offset];
  1581. }
  1582. info[axis].progress = create.clamp(0, 1, info[axis].interpolate(info[axis].current));
  1583. }
  1584. function measure(container, target = container, info) {
  1585. /**
  1586. * Find inset of target within scrollable container
  1587. */
  1588. info.x.targetOffset = 0;
  1589. info.y.targetOffset = 0;
  1590. if (target !== container) {
  1591. let node = target;
  1592. while (node && node !== container) {
  1593. info.x.targetOffset += node.offsetLeft;
  1594. info.y.targetOffset += node.offsetTop;
  1595. node = node.offsetParent;
  1596. }
  1597. }
  1598. info.x.targetLength =
  1599. target === container ? target.scrollWidth : target.clientWidth;
  1600. info.y.targetLength =
  1601. target === container ? target.scrollHeight : target.clientHeight;
  1602. info.x.containerLength = container.clientWidth;
  1603. info.y.containerLength = container.clientHeight;
  1604. /**
  1605. * In development mode ensure scroll containers aren't position: static as this makes
  1606. * it difficult to measure their relative positions.
  1607. */
  1608. if (process.env.NODE_ENV !== "production") {
  1609. if (container && target && target !== container) {
  1610. motionUtils.warnOnce(getComputedStyle(container).position !== "static", "Please ensure that the container has a non-static position, like 'relative', 'fixed', or 'absolute' to ensure scroll offset is calculated correctly.");
  1611. }
  1612. }
  1613. }
  1614. function createOnScrollHandler(element, onScroll, info, options = {}) {
  1615. return {
  1616. measure: () => measure(element, options.target, info),
  1617. update: (time) => {
  1618. updateScrollInfo(element, info, time);
  1619. if (options.offset || options.target) {
  1620. resolveOffsets(element, info, options);
  1621. }
  1622. },
  1623. notify: () => onScroll(info),
  1624. };
  1625. }
  1626. const scrollListeners = new WeakMap();
  1627. const resizeListeners = new WeakMap();
  1628. const onScrollHandlers = new WeakMap();
  1629. const getEventTarget = (element) => element === document.documentElement ? window : element;
  1630. function scrollInfo(onScroll, { container = document.documentElement, ...options } = {}) {
  1631. let containerHandlers = onScrollHandlers.get(container);
  1632. /**
  1633. * Get the onScroll handlers for this container.
  1634. * If one isn't found, create a new one.
  1635. */
  1636. if (!containerHandlers) {
  1637. containerHandlers = new Set();
  1638. onScrollHandlers.set(container, containerHandlers);
  1639. }
  1640. /**
  1641. * Create a new onScroll handler for the provided callback.
  1642. */
  1643. const info = createScrollInfo();
  1644. const containerHandler = createOnScrollHandler(container, onScroll, info, options);
  1645. containerHandlers.add(containerHandler);
  1646. /**
  1647. * Check if there's a scroll event listener for this container.
  1648. * If not, create one.
  1649. */
  1650. if (!scrollListeners.has(container)) {
  1651. const measureAll = () => {
  1652. for (const handler of containerHandlers)
  1653. handler.measure();
  1654. };
  1655. const updateAll = () => {
  1656. for (const handler of containerHandlers) {
  1657. handler.update(motionDom.frameData.timestamp);
  1658. }
  1659. };
  1660. const notifyAll = () => {
  1661. for (const handler of containerHandlers)
  1662. handler.notify();
  1663. };
  1664. const listener = () => {
  1665. motionDom.frame.read(measureAll, false, true);
  1666. motionDom.frame.read(updateAll, false, true);
  1667. motionDom.frame.update(notifyAll, false, true);
  1668. };
  1669. scrollListeners.set(container, listener);
  1670. const target = getEventTarget(container);
  1671. window.addEventListener("resize", listener, { passive: true });
  1672. if (container !== document.documentElement) {
  1673. resizeListeners.set(container, resize(container, listener));
  1674. }
  1675. target.addEventListener("scroll", listener, { passive: true });
  1676. }
  1677. const listener = scrollListeners.get(container);
  1678. motionDom.frame.read(listener, false, true);
  1679. return () => {
  1680. motionDom.cancelFrame(listener);
  1681. /**
  1682. * Check if we even have any handlers for this container.
  1683. */
  1684. const currentHandlers = onScrollHandlers.get(container);
  1685. if (!currentHandlers)
  1686. return;
  1687. currentHandlers.delete(containerHandler);
  1688. if (currentHandlers.size)
  1689. return;
  1690. /**
  1691. * If no more handlers, remove the scroll listener too.
  1692. */
  1693. const scrollListener = scrollListeners.get(container);
  1694. scrollListeners.delete(container);
  1695. if (scrollListener) {
  1696. getEventTarget(container).removeEventListener("scroll", scrollListener);
  1697. resizeListeners.get(container)?.();
  1698. window.removeEventListener("resize", scrollListener);
  1699. }
  1700. };
  1701. }
  1702. function scrollTimelineFallback({ source, container, axis = "y", }) {
  1703. // Support legacy source argument. Deprecate later.
  1704. if (source)
  1705. container = source;
  1706. // ScrollTimeline records progress as a percentage CSSUnitValue
  1707. const currentTime = { value: 0 };
  1708. const cancel = scrollInfo((info) => {
  1709. currentTime.value = info[axis].progress * 100;
  1710. }, { container, axis });
  1711. return { currentTime, cancel };
  1712. }
  1713. const timelineCache = new Map();
  1714. function getTimeline({ source, container = document.documentElement, axis = "y", } = {}) {
  1715. // Support legacy source argument. Deprecate later.
  1716. if (source)
  1717. container = source;
  1718. if (!timelineCache.has(container)) {
  1719. timelineCache.set(container, {});
  1720. }
  1721. const elementCache = timelineCache.get(container);
  1722. if (!elementCache[axis]) {
  1723. elementCache[axis] = motionDom.supportsScrollTimeline()
  1724. ? new ScrollTimeline({ source: container, axis })
  1725. : scrollTimelineFallback({ source: container, axis });
  1726. }
  1727. return elementCache[axis];
  1728. }
  1729. /**
  1730. * If the onScroll function has two arguments, it's expecting
  1731. * more specific information about the scroll from scrollInfo.
  1732. */
  1733. function isOnScrollWithInfo(onScroll) {
  1734. return onScroll.length === 2;
  1735. }
  1736. /**
  1737. * Currently, we only support element tracking with `scrollInfo`, though in
  1738. * the future we can also offer ViewTimeline support.
  1739. */
  1740. function needsElementTracking(options) {
  1741. return options && (options.target || options.offset);
  1742. }
  1743. function scrollFunction(onScroll, options) {
  1744. if (isOnScrollWithInfo(onScroll) || needsElementTracking(options)) {
  1745. return scrollInfo((info) => {
  1746. onScroll(info[options.axis].progress, info);
  1747. }, options);
  1748. }
  1749. else {
  1750. return observeTimeline(onScroll, getTimeline(options));
  1751. }
  1752. }
  1753. function scrollAnimation(animation, options) {
  1754. animation.flatten();
  1755. if (needsElementTracking(options)) {
  1756. animation.pause();
  1757. return scrollInfo((info) => {
  1758. animation.time = animation.duration * info[options.axis].progress;
  1759. }, options);
  1760. }
  1761. else {
  1762. const timeline = getTimeline(options);
  1763. if (animation.attachTimeline) {
  1764. return animation.attachTimeline(timeline, (valueAnimation) => {
  1765. valueAnimation.pause();
  1766. return observeTimeline((progress) => {
  1767. valueAnimation.time = valueAnimation.duration * progress;
  1768. }, timeline);
  1769. });
  1770. }
  1771. else {
  1772. return motionUtils.noop;
  1773. }
  1774. }
  1775. }
  1776. function scroll(onScroll, { axis = "y", ...options } = {}) {
  1777. const optionsWithDefaults = { axis, ...options };
  1778. return typeof onScroll === "function"
  1779. ? scrollFunction(onScroll, optionsWithDefaults)
  1780. : scrollAnimation(onScroll, optionsWithDefaults);
  1781. }
  1782. const thresholds = {
  1783. some: 0,
  1784. all: 1,
  1785. };
  1786. function inView(elementOrSelector, onStart, { root, margin: rootMargin, amount = "some" } = {}) {
  1787. const elements = motionDom.resolveElements(elementOrSelector);
  1788. const activeIntersections = new WeakMap();
  1789. const onIntersectionChange = (entries) => {
  1790. entries.forEach((entry) => {
  1791. const onEnd = activeIntersections.get(entry.target);
  1792. /**
  1793. * If there's no change to the intersection, we don't need to
  1794. * do anything here.
  1795. */
  1796. if (entry.isIntersecting === Boolean(onEnd))
  1797. return;
  1798. if (entry.isIntersecting) {
  1799. const newOnEnd = onStart(entry.target, entry);
  1800. if (typeof newOnEnd === "function") {
  1801. activeIntersections.set(entry.target, newOnEnd);
  1802. }
  1803. else {
  1804. observer.unobserve(entry.target);
  1805. }
  1806. }
  1807. else if (typeof onEnd === "function") {
  1808. onEnd(entry);
  1809. activeIntersections.delete(entry.target);
  1810. }
  1811. });
  1812. };
  1813. const observer = new IntersectionObserver(onIntersectionChange, {
  1814. root,
  1815. rootMargin,
  1816. threshold: typeof amount === "number" ? amount : thresholds[amount],
  1817. });
  1818. elements.forEach((element) => observer.observe(element));
  1819. return () => observer.disconnect();
  1820. }
  1821. function steps(numSteps, direction = "end") {
  1822. return (progress) => {
  1823. progress =
  1824. direction === "end"
  1825. ? Math.min(progress, 0.999)
  1826. : Math.max(progress, 0.001);
  1827. const expanded = progress * numSteps;
  1828. const rounded = direction === "end" ? Math.floor(expanded) : Math.ceil(expanded);
  1829. return create.clamp(0, 1, rounded / numSteps);
  1830. };
  1831. }
  1832. function getOriginIndex(from, total) {
  1833. if (from === "first") {
  1834. return 0;
  1835. }
  1836. else {
  1837. const lastIndex = total - 1;
  1838. return from === "last" ? lastIndex : lastIndex / 2;
  1839. }
  1840. }
  1841. function stagger(duration = 0.1, { startDelay = 0, from = 0, ease } = {}) {
  1842. return (i, total) => {
  1843. const fromIndex = typeof from === "number" ? from : getOriginIndex(from, total);
  1844. const distance = Math.abs(fromIndex - i);
  1845. let delay = duration * distance;
  1846. if (ease) {
  1847. const maxDelay = total * duration;
  1848. const easingFunction = create.easingDefinitionToFunction(ease);
  1849. delay = easingFunction(delay / maxDelay) * maxDelay;
  1850. }
  1851. return startDelay + delay;
  1852. };
  1853. }
  1854. const createMinimalMotionComponent =
  1855. /*@__PURE__*/ create.createMotionComponentFactory();
  1856. const m = /*@__PURE__*/ createDOMMotionComponentProxy(createMinimalMotionComponent);
  1857. function useUnmountEffect(callback) {
  1858. return React.useEffect(() => () => callback(), []);
  1859. }
  1860. /**
  1861. * @public
  1862. */
  1863. const domAnimation = {
  1864. renderer: create.createDomVisualElement,
  1865. ...create.animations,
  1866. ...create.gestureAnimations,
  1867. };
  1868. /**
  1869. * @public
  1870. */
  1871. const domMax = {
  1872. ...domAnimation,
  1873. ...create.drag,
  1874. ...create.layout,
  1875. };
  1876. /**
  1877. * @public
  1878. */
  1879. const domMin = {
  1880. renderer: create.createDomVisualElement,
  1881. ...create.animations,
  1882. };
  1883. function useMotionValueEvent(value, event, callback) {
  1884. /**
  1885. * useInsertionEffect will create subscriptions before any other
  1886. * effects will run. Effects run upwards through the tree so it
  1887. * can be that binding a useLayoutEffect higher up the tree can
  1888. * miss changes from lower down the tree.
  1889. */
  1890. React.useInsertionEffect(() => value.on(event, callback), [value, event, callback]);
  1891. }
  1892. function refWarning(name, ref) {
  1893. motionUtils.warning(Boolean(!ref || ref.current), `You have defined a ${name} options but the provided ref is not yet hydrated, probably because it's defined higher up the tree. Try calling useScroll() in the same component as the ref, or setting its \`layoutEffect: false\` option.`);
  1894. }
  1895. const createScrollMotionValues = () => ({
  1896. scrollX: motionDom.motionValue(0),
  1897. scrollY: motionDom.motionValue(0),
  1898. scrollXProgress: motionDom.motionValue(0),
  1899. scrollYProgress: motionDom.motionValue(0),
  1900. });
  1901. function useScroll({ container, target, layoutEffect = true, ...options } = {}) {
  1902. const values = create.useConstant(createScrollMotionValues);
  1903. const useLifecycleEffect = layoutEffect
  1904. ? create.useIsomorphicLayoutEffect
  1905. : React.useEffect;
  1906. useLifecycleEffect(() => {
  1907. refWarning("target", target);
  1908. refWarning("container", container);
  1909. return scroll((_progress, { x, y, }) => {
  1910. values.scrollX.set(x.current);
  1911. values.scrollXProgress.set(x.progress);
  1912. values.scrollY.set(y.current);
  1913. values.scrollYProgress.set(y.progress);
  1914. }, {
  1915. ...options,
  1916. container: container?.current || undefined,
  1917. target: target?.current || undefined,
  1918. });
  1919. }, [container, target, JSON.stringify(options.offset)]);
  1920. return values;
  1921. }
  1922. /**
  1923. * @deprecated useElementScroll is deprecated. Convert to useScroll({ container: ref })
  1924. */
  1925. function useElementScroll(ref) {
  1926. if (process.env.NODE_ENV === "development") {
  1927. motionUtils.warnOnce(false, "useElementScroll is deprecated. Convert to useScroll({ container: ref }).");
  1928. }
  1929. return useScroll({ container: ref });
  1930. }
  1931. /**
  1932. * @deprecated useViewportScroll is deprecated. Convert to useScroll()
  1933. */
  1934. function useViewportScroll() {
  1935. if (process.env.NODE_ENV !== "production") {
  1936. motionUtils.warnOnce(false, "useViewportScroll is deprecated. Convert to useScroll().");
  1937. }
  1938. return useScroll();
  1939. }
  1940. /**
  1941. * Combine multiple motion values into a new one using a string template literal.
  1942. *
  1943. * ```jsx
  1944. * import {
  1945. * motion,
  1946. * useSpring,
  1947. * useMotionValue,
  1948. * useMotionTemplate
  1949. * } from "framer-motion"
  1950. *
  1951. * function Component() {
  1952. * const shadowX = useSpring(0)
  1953. * const shadowY = useMotionValue(0)
  1954. * const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))`
  1955. *
  1956. * return <motion.div style={{ filter: shadow }} />
  1957. * }
  1958. * ```
  1959. *
  1960. * @public
  1961. */
  1962. function useMotionTemplate(fragments, ...values) {
  1963. /**
  1964. * Create a function that will build a string from the latest motion values.
  1965. */
  1966. const numFragments = fragments.length;
  1967. function buildValue() {
  1968. let output = ``;
  1969. for (let i = 0; i < numFragments; i++) {
  1970. output += fragments[i];
  1971. const value = values[i];
  1972. if (value) {
  1973. output += create.isMotionValue(value) ? value.get() : value;
  1974. }
  1975. }
  1976. return output;
  1977. }
  1978. return useCombineMotionValues(values.filter(create.isMotionValue), buildValue);
  1979. }
  1980. function useSpring(source, config = {}) {
  1981. const { isStatic } = React.useContext(create.MotionConfigContext);
  1982. const activeSpringAnimation = React.useRef(null);
  1983. const initialValue = create.useConstant(() => create.isMotionValue(source) ? source.get() : source);
  1984. const unit = create.useConstant(() => typeof initialValue === "string"
  1985. ? initialValue.replace(/[\d.-]/g, "")
  1986. : undefined);
  1987. const value = useMotionValue(initialValue);
  1988. const latestValue = React.useRef(initialValue);
  1989. const latestSetter = React.useRef(motionUtils.noop);
  1990. const startAnimation = () => {
  1991. stopAnimation();
  1992. activeSpringAnimation.current = create.animateValue({
  1993. keyframes: [asNumber(value.get()), asNumber(latestValue.current)],
  1994. velocity: value.getVelocity(),
  1995. type: "spring",
  1996. restDelta: 0.001,
  1997. restSpeed: 0.01,
  1998. ...config,
  1999. onUpdate: latestSetter.current,
  2000. });
  2001. };
  2002. const stopAnimation = () => {
  2003. if (activeSpringAnimation.current) {
  2004. activeSpringAnimation.current.stop();
  2005. }
  2006. };
  2007. React.useInsertionEffect(() => {
  2008. return value.attach((v, set) => {
  2009. if (isStatic)
  2010. return set(v);
  2011. latestValue.current = v;
  2012. latestSetter.current = (latest) => set(parseValue(latest, unit));
  2013. motionDom.frame.postRender(startAnimation);
  2014. return value.get();
  2015. }, stopAnimation);
  2016. }, [JSON.stringify(config)]);
  2017. create.useIsomorphicLayoutEffect(() => {
  2018. if (create.isMotionValue(source)) {
  2019. return source.on("change", (v) => value.set(parseValue(v, unit)));
  2020. }
  2021. }, [value, unit]);
  2022. return value;
  2023. }
  2024. function parseValue(v, unit) {
  2025. return unit ? v + unit : v;
  2026. }
  2027. function asNumber(v) {
  2028. return typeof v === "number" ? v : parseFloat(v);
  2029. }
  2030. function useAnimationFrame(callback) {
  2031. const initialTimestamp = React.useRef(0);
  2032. const { isStatic } = React.useContext(create.MotionConfigContext);
  2033. React.useEffect(() => {
  2034. if (isStatic)
  2035. return;
  2036. const provideTimeSinceStart = ({ timestamp, delta }) => {
  2037. if (!initialTimestamp.current)
  2038. initialTimestamp.current = timestamp;
  2039. callback(timestamp - initialTimestamp.current, delta);
  2040. };
  2041. motionDom.frame.update(provideTimeSinceStart, true);
  2042. return () => motionDom.cancelFrame(provideTimeSinceStart);
  2043. }, [callback]);
  2044. }
  2045. function useTime() {
  2046. const time = useMotionValue(0);
  2047. useAnimationFrame((t) => time.set(t));
  2048. return time;
  2049. }
  2050. /**
  2051. * Creates a `MotionValue` that updates when the velocity of the provided `MotionValue` changes.
  2052. *
  2053. * ```javascript
  2054. * const x = useMotionValue(0)
  2055. * const xVelocity = useVelocity(x)
  2056. * const xAcceleration = useVelocity(xVelocity)
  2057. * ```
  2058. *
  2059. * @public
  2060. */
  2061. function useVelocity(value) {
  2062. const velocity = useMotionValue(value.getVelocity());
  2063. const updateVelocity = () => {
  2064. const latest = value.getVelocity();
  2065. velocity.set(latest);
  2066. /**
  2067. * If we still have velocity, schedule an update for the next frame
  2068. * to keep checking until it is zero.
  2069. */
  2070. if (latest)
  2071. motionDom.frame.update(updateVelocity);
  2072. };
  2073. useMotionValueEvent(value, "change", () => {
  2074. // Schedule an update to this value at the end of the current frame.
  2075. motionDom.frame.update(updateVelocity, false, true);
  2076. });
  2077. return velocity;
  2078. }
  2079. function getWillChangeName(name) {
  2080. if (create.transformProps.has(name)) {
  2081. return "transform";
  2082. }
  2083. else if (create.acceleratedValues.has(name)) {
  2084. return create.camelToDash(name);
  2085. }
  2086. }
  2087. class WillChangeMotionValue extends motionDom.MotionValue {
  2088. constructor() {
  2089. super(...arguments);
  2090. this.values = [];
  2091. }
  2092. add(name) {
  2093. const styleName = getWillChangeName(name);
  2094. if (styleName) {
  2095. motionUtils.addUniqueItem(this.values, styleName);
  2096. this.update();
  2097. }
  2098. }
  2099. update() {
  2100. this.set(this.values.length ? this.values.join(", ") : "auto");
  2101. }
  2102. }
  2103. function useWillChange() {
  2104. return create.useConstant(() => new WillChangeMotionValue("auto"));
  2105. }
  2106. /**
  2107. * A hook that returns `true` if we should be using reduced motion based on the current device's Reduced Motion setting.
  2108. *
  2109. * This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing
  2110. * `x`/`y` animations with `opacity`, disabling the autoplay of background videos, or turning off parallax motion.
  2111. *
  2112. * It will actively respond to changes and re-render your components with the latest setting.
  2113. *
  2114. * ```jsx
  2115. * export function Sidebar({ isOpen }) {
  2116. * const shouldReduceMotion = useReducedMotion()
  2117. * const closedX = shouldReduceMotion ? 0 : "-100%"
  2118. *
  2119. * return (
  2120. * <motion.div animate={{
  2121. * opacity: isOpen ? 1 : 0,
  2122. * x: isOpen ? 0 : closedX
  2123. * }} />
  2124. * )
  2125. * }
  2126. * ```
  2127. *
  2128. * @return boolean
  2129. *
  2130. * @public
  2131. */
  2132. function useReducedMotion() {
  2133. /**
  2134. * Lazy initialisation of prefersReducedMotion
  2135. */
  2136. !create.hasReducedMotionListener.current && create.initPrefersReducedMotion();
  2137. const [shouldReduceMotion] = React.useState(create.prefersReducedMotion.current);
  2138. if (process.env.NODE_ENV !== "production") {
  2139. motionUtils.warnOnce(shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.");
  2140. }
  2141. /**
  2142. * TODO See if people miss automatically updating shouldReduceMotion setting
  2143. */
  2144. return shouldReduceMotion;
  2145. }
  2146. function useReducedMotionConfig() {
  2147. const reducedMotionPreference = useReducedMotion();
  2148. const { reducedMotion } = React.useContext(create.MotionConfigContext);
  2149. if (reducedMotion === "never") {
  2150. return false;
  2151. }
  2152. else if (reducedMotion === "always") {
  2153. return true;
  2154. }
  2155. else {
  2156. return reducedMotionPreference;
  2157. }
  2158. }
  2159. function stopAnimation(visualElement) {
  2160. visualElement.values.forEach((value) => value.stop());
  2161. }
  2162. function setVariants(visualElement, variantLabels) {
  2163. const reversedLabels = [...variantLabels].reverse();
  2164. reversedLabels.forEach((key) => {
  2165. const variant = visualElement.getVariant(key);
  2166. variant && create.setTarget(visualElement, variant);
  2167. if (visualElement.variantChildren) {
  2168. visualElement.variantChildren.forEach((child) => {
  2169. setVariants(child, variantLabels);
  2170. });
  2171. }
  2172. });
  2173. }
  2174. function setValues(visualElement, definition) {
  2175. if (Array.isArray(definition)) {
  2176. return setVariants(visualElement, definition);
  2177. }
  2178. else if (typeof definition === "string") {
  2179. return setVariants(visualElement, [definition]);
  2180. }
  2181. else {
  2182. create.setTarget(visualElement, definition);
  2183. }
  2184. }
  2185. /**
  2186. * @public
  2187. */
  2188. function animationControls() {
  2189. /**
  2190. * Track whether the host component has mounted.
  2191. */
  2192. let hasMounted = false;
  2193. /**
  2194. * A collection of linked component animation controls.
  2195. */
  2196. const subscribers = new Set();
  2197. const controls = {
  2198. subscribe(visualElement) {
  2199. subscribers.add(visualElement);
  2200. return () => void subscribers.delete(visualElement);
  2201. },
  2202. start(definition, transitionOverride) {
  2203. motionUtils.invariant(hasMounted, "controls.start() should only be called after a component has mounted. Consider calling within a useEffect hook.");
  2204. const animations = [];
  2205. subscribers.forEach((visualElement) => {
  2206. animations.push(create.animateVisualElement(visualElement, definition, {
  2207. transitionOverride,
  2208. }));
  2209. });
  2210. return Promise.all(animations);
  2211. },
  2212. set(definition) {
  2213. motionUtils.invariant(hasMounted, "controls.set() should only be called after a component has mounted. Consider calling within a useEffect hook.");
  2214. return subscribers.forEach((visualElement) => {
  2215. setValues(visualElement, definition);
  2216. });
  2217. },
  2218. stop() {
  2219. subscribers.forEach((visualElement) => {
  2220. stopAnimation(visualElement);
  2221. });
  2222. },
  2223. mount() {
  2224. hasMounted = true;
  2225. return () => {
  2226. hasMounted = false;
  2227. controls.stop();
  2228. };
  2229. },
  2230. };
  2231. return controls;
  2232. }
  2233. function useAnimate() {
  2234. const scope = create.useConstant(() => ({
  2235. current: null, // Will be hydrated by React
  2236. animations: [],
  2237. }));
  2238. const animate = create.useConstant(() => createScopedAnimate(scope));
  2239. useUnmountEffect(() => {
  2240. scope.animations.forEach((animation) => animation.stop());
  2241. });
  2242. return [scope, animate];
  2243. }
  2244. function useAnimateMini() {
  2245. const scope = create.useConstant(() => ({
  2246. current: null, // Will be hydrated by React
  2247. animations: [],
  2248. }));
  2249. const animate = create.useConstant(() => createScopedWaapiAnimate(scope));
  2250. useUnmountEffect(() => {
  2251. scope.animations.forEach((animation) => animation.stop());
  2252. });
  2253. return [scope, animate];
  2254. }
  2255. /**
  2256. * Creates `AnimationControls`, which can be used to manually start, stop
  2257. * and sequence animations on one or more components.
  2258. *
  2259. * The returned `AnimationControls` should be passed to the `animate` property
  2260. * of the components you want to animate.
  2261. *
  2262. * These components can then be animated with the `start` method.
  2263. *
  2264. * ```jsx
  2265. * import * as React from 'react'
  2266. * import { motion, useAnimation } from 'framer-motion'
  2267. *
  2268. * export function MyComponent(props) {
  2269. * const controls = useAnimation()
  2270. *
  2271. * controls.start({
  2272. * x: 100,
  2273. * transition: { duration: 0.5 },
  2274. * })
  2275. *
  2276. * return <motion.div animate={controls} />
  2277. * }
  2278. * ```
  2279. *
  2280. * @returns Animation controller with `start` and `stop` methods
  2281. *
  2282. * @public
  2283. */
  2284. function useAnimationControls() {
  2285. const controls = create.useConstant(animationControls);
  2286. create.useIsomorphicLayoutEffect(controls.mount, []);
  2287. return controls;
  2288. }
  2289. const useAnimation = useAnimationControls;
  2290. function usePresenceData() {
  2291. const context = React.useContext(create.PresenceContext);
  2292. return context ? context.custom : undefined;
  2293. }
  2294. /**
  2295. * Attaches an event listener directly to the provided DOM element.
  2296. *
  2297. * Bypassing React's event system can be desirable, for instance when attaching non-passive
  2298. * event handlers.
  2299. *
  2300. * ```jsx
  2301. * const ref = useRef(null)
  2302. *
  2303. * useDomEvent(ref, 'wheel', onWheel, { passive: false })
  2304. *
  2305. * return <div ref={ref} />
  2306. * ```
  2307. *
  2308. * @param ref - React.RefObject that's been provided to the element you want to bind the listener to.
  2309. * @param eventName - Name of the event you want listen for.
  2310. * @param handler - Function to fire when receiving the event.
  2311. * @param options - Options to pass to `Event.addEventListener`.
  2312. *
  2313. * @public
  2314. */
  2315. function useDomEvent(ref, eventName, handler, options) {
  2316. React.useEffect(() => {
  2317. const element = ref.current;
  2318. if (handler && element) {
  2319. return create.addDomEvent(element, eventName, handler, options);
  2320. }
  2321. }, [ref, eventName, handler, options]);
  2322. }
  2323. /**
  2324. * Can manually trigger a drag gesture on one or more `drag`-enabled `motion` components.
  2325. *
  2326. * ```jsx
  2327. * const dragControls = useDragControls()
  2328. *
  2329. * function startDrag(event) {
  2330. * dragControls.start(event, { snapToCursor: true })
  2331. * }
  2332. *
  2333. * return (
  2334. * <>
  2335. * <div onPointerDown={startDrag} />
  2336. * <motion.div drag="x" dragControls={dragControls} />
  2337. * </>
  2338. * )
  2339. * ```
  2340. *
  2341. * @public
  2342. */
  2343. class DragControls {
  2344. constructor() {
  2345. this.componentControls = new Set();
  2346. }
  2347. /**
  2348. * Subscribe a component's internal `VisualElementDragControls` to the user-facing API.
  2349. *
  2350. * @internal
  2351. */
  2352. subscribe(controls) {
  2353. this.componentControls.add(controls);
  2354. return () => this.componentControls.delete(controls);
  2355. }
  2356. /**
  2357. * Start a drag gesture on every `motion` component that has this set of drag controls
  2358. * passed into it via the `dragControls` prop.
  2359. *
  2360. * ```jsx
  2361. * dragControls.start(e, {
  2362. * snapToCursor: true
  2363. * })
  2364. * ```
  2365. *
  2366. * @param event - PointerEvent
  2367. * @param options - Options
  2368. *
  2369. * @public
  2370. */
  2371. start(event, options) {
  2372. this.componentControls.forEach((controls) => {
  2373. controls.start(event.nativeEvent || event, options);
  2374. });
  2375. }
  2376. }
  2377. const createDragControls = () => new DragControls();
  2378. /**
  2379. * Usually, dragging is initiated by pressing down on a `motion` component with a `drag` prop
  2380. * and moving it. For some use-cases, for instance clicking at an arbitrary point on a video scrubber, we
  2381. * might want to initiate that dragging from a different component than the draggable one.
  2382. *
  2383. * By creating a `dragControls` using the `useDragControls` hook, we can pass this into
  2384. * the draggable component's `dragControls` prop. It exposes a `start` method
  2385. * that can start dragging from pointer events on other components.
  2386. *
  2387. * ```jsx
  2388. * const dragControls = useDragControls()
  2389. *
  2390. * function startDrag(event) {
  2391. * dragControls.start(event, { snapToCursor: true })
  2392. * }
  2393. *
  2394. * return (
  2395. * <>
  2396. * <div onPointerDown={startDrag} />
  2397. * <motion.div drag="x" dragControls={dragControls} />
  2398. * </>
  2399. * )
  2400. * ```
  2401. *
  2402. * @public
  2403. */
  2404. function useDragControls() {
  2405. return create.useConstant(createDragControls);
  2406. }
  2407. /**
  2408. * Checks if a component is a `motion` component.
  2409. */
  2410. function isMotionComponent(component) {
  2411. return (component !== null &&
  2412. typeof component === "object" &&
  2413. create.motionComponentSymbol in component);
  2414. }
  2415. /**
  2416. * Unwraps a `motion` component and returns either a string for `motion.div` or
  2417. * the React component for `motion(Component)`.
  2418. *
  2419. * If the component is not a `motion` component it returns undefined.
  2420. */
  2421. function unwrapMotionComponent(component) {
  2422. if (isMotionComponent(component)) {
  2423. return component[create.motionComponentSymbol];
  2424. }
  2425. return undefined;
  2426. }
  2427. function useInstantLayoutTransition() {
  2428. return startTransition;
  2429. }
  2430. function startTransition(callback) {
  2431. if (!create.rootProjectionNode.current)
  2432. return;
  2433. create.rootProjectionNode.current.isUpdating = false;
  2434. create.rootProjectionNode.current.blockUpdate();
  2435. callback && callback();
  2436. }
  2437. function useResetProjection() {
  2438. const reset = React.useCallback(() => {
  2439. const root = create.rootProjectionNode.current;
  2440. if (!root)
  2441. return;
  2442. root.resetTree();
  2443. }, []);
  2444. return reset;
  2445. }
  2446. /**
  2447. * Cycles through a series of visual properties. Can be used to toggle between or cycle through animations. It works similar to `useState` in React. It is provided an initial array of possible states, and returns an array of two arguments.
  2448. *
  2449. * An index value can be passed to the returned `cycle` function to cycle to a specific index.
  2450. *
  2451. * ```jsx
  2452. * import * as React from "react"
  2453. * import { motion, useCycle } from "framer-motion"
  2454. *
  2455. * export const MyComponent = () => {
  2456. * const [x, cycleX] = useCycle(0, 50, 100)
  2457. *
  2458. * return (
  2459. * <motion.div
  2460. * animate={{ x: x }}
  2461. * onTap={() => cycleX()}
  2462. * />
  2463. * )
  2464. * }
  2465. * ```
  2466. *
  2467. * @param items - items to cycle through
  2468. * @returns [currentState, cycleState]
  2469. *
  2470. * @public
  2471. */
  2472. function useCycle(...items) {
  2473. const index = React.useRef(0);
  2474. const [item, setItem] = React.useState(items[index.current]);
  2475. const runCycle = React.useCallback((next) => {
  2476. index.current =
  2477. typeof next !== "number"
  2478. ? wrap(0, items.length, index.current + 1)
  2479. : next;
  2480. setItem(items[index.current]);
  2481. },
  2482. // The array will change on each call, but by putting items.length at
  2483. // the front of this array, we guarantee the dependency comparison will match up
  2484. // eslint-disable-next-line react-hooks/exhaustive-deps
  2485. [items.length, ...items]);
  2486. return [item, runCycle];
  2487. }
  2488. function useInView(ref, { root, margin, amount, once = false, initial = false, } = {}) {
  2489. const [isInView, setInView] = React.useState(initial);
  2490. React.useEffect(() => {
  2491. if (!ref.current || (once && isInView))
  2492. return;
  2493. const onEnter = () => {
  2494. setInView(true);
  2495. return once ? undefined : () => setInView(false);
  2496. };
  2497. const options = {
  2498. root: (root && root.current) || undefined,
  2499. margin,
  2500. amount,
  2501. };
  2502. return inView(ref.current, onEnter, options);
  2503. }, [root, ref, margin, once, amount]);
  2504. return isInView;
  2505. }
  2506. function useInstantTransition() {
  2507. const [forceUpdate, forcedRenderCount] = useForceUpdate();
  2508. const startInstantLayoutTransition = useInstantLayoutTransition();
  2509. const unlockOnFrameRef = React.useRef(-1);
  2510. React.useEffect(() => {
  2511. /**
  2512. * Unblock after two animation frames, otherwise this will unblock too soon.
  2513. */
  2514. motionDom.frame.postRender(() => motionDom.frame.postRender(() => {
  2515. /**
  2516. * If the callback has been called again after the effect
  2517. * triggered this 2 frame delay, don't unblock animations. This
  2518. * prevents the previous effect from unblocking the current
  2519. * instant transition too soon. This becomes more likely when
  2520. * used in conjunction with React.startTransition().
  2521. */
  2522. if (forcedRenderCount !== unlockOnFrameRef.current)
  2523. return;
  2524. create.instantAnimationState.current = false;
  2525. }));
  2526. }, [forcedRenderCount]);
  2527. return (callback) => {
  2528. startInstantLayoutTransition(() => {
  2529. create.instantAnimationState.current = true;
  2530. forceUpdate();
  2531. callback();
  2532. unlockOnFrameRef.current = forcedRenderCount + 1;
  2533. });
  2534. };
  2535. }
  2536. function disableInstantTransitions() {
  2537. create.instantAnimationState.current = false;
  2538. }
  2539. const appearAnimationStore = new Map();
  2540. const appearComplete = new Map();
  2541. const appearStoreId = (elementId, valueName) => {
  2542. const key = create.transformProps.has(valueName) ? "transform" : valueName;
  2543. return `${elementId}: ${key}`;
  2544. };
  2545. function handoffOptimizedAppearAnimation(elementId, valueName, frame) {
  2546. const storeId = appearStoreId(elementId, valueName);
  2547. const optimisedAnimation = appearAnimationStore.get(storeId);
  2548. if (!optimisedAnimation) {
  2549. return null;
  2550. }
  2551. const { animation, startTime } = optimisedAnimation;
  2552. function cancelAnimation() {
  2553. window.MotionCancelOptimisedAnimation?.(elementId, valueName, frame);
  2554. }
  2555. /**
  2556. * We can cancel the animation once it's finished now that we've synced
  2557. * with Motion.
  2558. *
  2559. * Prefer onfinish over finished as onfinish is backwards compatible with
  2560. * older browsers.
  2561. */
  2562. animation.onfinish = cancelAnimation;
  2563. if (startTime === null || window.MotionHandoffIsComplete?.(elementId)) {
  2564. /**
  2565. * If the startTime is null, this animation is the Paint Ready detection animation
  2566. * and we can cancel it immediately without handoff.
  2567. *
  2568. * Or if we've already handed off the animation then we're now interrupting it.
  2569. * In which case we need to cancel it.
  2570. */
  2571. cancelAnimation();
  2572. return null;
  2573. }
  2574. else {
  2575. return startTime;
  2576. }
  2577. }
  2578. /**
  2579. * A single time to use across all animations to manually set startTime
  2580. * and ensure they're all in sync.
  2581. */
  2582. let startFrameTime;
  2583. /**
  2584. * A dummy animation to detect when Chrome is ready to start
  2585. * painting the page and hold off from triggering the real animation
  2586. * until then. We only need one animation to detect paint ready.
  2587. *
  2588. * https://bugs.chromium.org/p/chromium/issues/detail?id=1406850
  2589. */
  2590. let readyAnimation;
  2591. /**
  2592. * Keep track of animations that were suspended vs cancelled so we
  2593. * can easily resume them when we're done measuring layout.
  2594. */
  2595. const suspendedAnimations = new Set();
  2596. function resumeSuspendedAnimations() {
  2597. suspendedAnimations.forEach((data) => {
  2598. data.animation.play();
  2599. data.animation.startTime = data.startTime;
  2600. });
  2601. suspendedAnimations.clear();
  2602. }
  2603. function startOptimizedAppearAnimation(element, name, keyframes, options, onReady) {
  2604. // Prevent optimised appear animations if Motion has already started animating.
  2605. if (window.MotionIsMounted) {
  2606. return;
  2607. }
  2608. const id = element.dataset[create.optimizedAppearDataId];
  2609. if (!id)
  2610. return;
  2611. window.MotionHandoffAnimation = handoffOptimizedAppearAnimation;
  2612. const storeId = appearStoreId(id, name);
  2613. if (!readyAnimation) {
  2614. readyAnimation = motionDom.startWaapiAnimation(element, name, [keyframes[0], keyframes[0]],
  2615. /**
  2616. * 10 secs is basically just a super-safe duration to give Chrome
  2617. * long enough to get the animation ready.
  2618. */
  2619. { duration: 10000, ease: "linear" });
  2620. appearAnimationStore.set(storeId, {
  2621. animation: readyAnimation,
  2622. startTime: null,
  2623. });
  2624. /**
  2625. * If there's no readyAnimation then there's been no instantiation
  2626. * of handoff animations.
  2627. */
  2628. window.MotionHandoffAnimation = handoffOptimizedAppearAnimation;
  2629. window.MotionHasOptimisedAnimation = (elementId, valueName) => {
  2630. if (!elementId)
  2631. return false;
  2632. /**
  2633. * Keep a map of elementIds that have started animating. We check
  2634. * via ID instead of Element because of hydration errors and
  2635. * pre-hydration checks. We also actively record IDs as they start
  2636. * animating rather than simply checking for data-appear-id as
  2637. * this attrbute might be present but not lead to an animation, for
  2638. * instance if the element's appear animation is on a different
  2639. * breakpoint.
  2640. */
  2641. if (!valueName) {
  2642. return appearComplete.has(elementId);
  2643. }
  2644. const animationId = appearStoreId(elementId, valueName);
  2645. return Boolean(appearAnimationStore.get(animationId));
  2646. };
  2647. window.MotionHandoffMarkAsComplete = (elementId) => {
  2648. if (appearComplete.has(elementId)) {
  2649. appearComplete.set(elementId, true);
  2650. }
  2651. };
  2652. window.MotionHandoffIsComplete = (elementId) => {
  2653. return appearComplete.get(elementId) === true;
  2654. };
  2655. /**
  2656. * We only need to cancel transform animations as
  2657. * they're the ones that will interfere with the
  2658. * layout animation measurements.
  2659. */
  2660. window.MotionCancelOptimisedAnimation = (elementId, valueName, frame, canResume) => {
  2661. const animationId = appearStoreId(elementId, valueName);
  2662. const data = appearAnimationStore.get(animationId);
  2663. if (!data)
  2664. return;
  2665. if (frame && canResume === undefined) {
  2666. /**
  2667. * Wait until the end of the subsequent frame to cancel the animation
  2668. * to ensure we don't remove the animation before the main thread has
  2669. * had a chance to resolve keyframes and render.
  2670. */
  2671. frame.postRender(() => {
  2672. frame.postRender(() => {
  2673. data.animation.cancel();
  2674. });
  2675. });
  2676. }
  2677. else {
  2678. data.animation.cancel();
  2679. }
  2680. if (frame && canResume) {
  2681. suspendedAnimations.add(data);
  2682. frame.render(resumeSuspendedAnimations);
  2683. }
  2684. else {
  2685. appearAnimationStore.delete(animationId);
  2686. /**
  2687. * If there are no more animations left, we can remove the cancel function.
  2688. * This will let us know when we can stop checking for conflicting layout animations.
  2689. */
  2690. if (!appearAnimationStore.size) {
  2691. window.MotionCancelOptimisedAnimation = undefined;
  2692. }
  2693. }
  2694. };
  2695. window.MotionCheckAppearSync = (visualElement, valueName, value) => {
  2696. const appearId = create.getOptimisedAppearId(visualElement);
  2697. if (!appearId)
  2698. return;
  2699. const valueIsOptimised = window.MotionHasOptimisedAnimation?.(appearId, valueName);
  2700. const externalAnimationValue = visualElement.props.values?.[valueName];
  2701. if (!valueIsOptimised || !externalAnimationValue)
  2702. return;
  2703. const removeSyncCheck = value.on("change", (latestValue) => {
  2704. if (externalAnimationValue.get() !== latestValue) {
  2705. window.MotionCancelOptimisedAnimation?.(appearId, valueName);
  2706. removeSyncCheck();
  2707. }
  2708. });
  2709. return removeSyncCheck;
  2710. };
  2711. }
  2712. const startAnimation = () => {
  2713. readyAnimation.cancel();
  2714. const appearAnimation = motionDom.startWaapiAnimation(element, name, keyframes, options);
  2715. /**
  2716. * Record the time of the first started animation. We call performance.now() once
  2717. * here and once in handoff to ensure we're getting
  2718. * close to a frame-locked time. This keeps all animations in sync.
  2719. */
  2720. if (startFrameTime === undefined) {
  2721. startFrameTime = performance.now();
  2722. }
  2723. appearAnimation.startTime = startFrameTime;
  2724. appearAnimationStore.set(storeId, {
  2725. animation: appearAnimation,
  2726. startTime: startFrameTime,
  2727. });
  2728. if (onReady)
  2729. onReady(appearAnimation);
  2730. };
  2731. appearComplete.set(id, false);
  2732. if (readyAnimation.ready) {
  2733. readyAnimation.ready.then(startAnimation).catch(motionUtils.noop);
  2734. }
  2735. else {
  2736. startAnimation();
  2737. }
  2738. }
  2739. const createObject = () => ({});
  2740. class StateVisualElement extends create.VisualElement {
  2741. constructor() {
  2742. super(...arguments);
  2743. this.measureInstanceViewportBox = create.createBox;
  2744. }
  2745. build() { }
  2746. resetTransform() { }
  2747. restoreTransform() { }
  2748. removeValueFromRenderState() { }
  2749. renderInstance() { }
  2750. scrapeMotionValuesFromProps() {
  2751. return createObject();
  2752. }
  2753. getBaseTargetFromProps() {
  2754. return undefined;
  2755. }
  2756. readValueFromInstance(_state, key, options) {
  2757. return options.initialState[key] || 0;
  2758. }
  2759. sortInstanceNodePosition() {
  2760. return 0;
  2761. }
  2762. }
  2763. const useVisualState = create.makeUseVisualState({
  2764. scrapeMotionValuesFromProps: createObject,
  2765. createRenderState: createObject,
  2766. });
  2767. /**
  2768. * This is not an officially supported API and may be removed
  2769. * on any version.
  2770. */
  2771. function useAnimatedState(initialState) {
  2772. const [animationState, setAnimationState] = React.useState(initialState);
  2773. const visualState = useVisualState({}, false);
  2774. const element = create.useConstant(() => {
  2775. return new StateVisualElement({
  2776. props: {
  2777. onUpdate: (v) => {
  2778. setAnimationState({ ...v });
  2779. },
  2780. },
  2781. visualState,
  2782. presenceContext: null,
  2783. }, { initialState });
  2784. });
  2785. React.useLayoutEffect(() => {
  2786. element.mount({});
  2787. return () => element.unmount();
  2788. }, [element]);
  2789. const startAnimation = create.useConstant(() => (animationDefinition) => {
  2790. return create.animateVisualElement(element, animationDefinition);
  2791. });
  2792. return [animationState, startAnimation];
  2793. }
  2794. let id = 0;
  2795. const AnimateSharedLayout = ({ children }) => {
  2796. React__namespace.useEffect(() => {
  2797. motionUtils.invariant(false, "AnimateSharedLayout is deprecated: https://www.framer.com/docs/guide-upgrade/##shared-layout-animations");
  2798. }, []);
  2799. return (jsxRuntime.jsx(LayoutGroup, { id: create.useConstant(() => `asl-${id++}`), children: children }));
  2800. };
  2801. // Keep things reasonable and avoid scale: Infinity. In practise we might need
  2802. // to add another value, opacity, that could interpolate scaleX/Y [0,0.01] => [0,1]
  2803. // to simply hide content at unreasonable scales.
  2804. const maxScale = 100000;
  2805. const invertScale = (scale) => scale > 0.001 ? 1 / scale : maxScale;
  2806. let hasWarned = false;
  2807. /**
  2808. * Returns a `MotionValue` each for `scaleX` and `scaleY` that update with the inverse
  2809. * of their respective parent scales.
  2810. *
  2811. * This is useful for undoing the distortion of content when scaling a parent component.
  2812. *
  2813. * By default, `useInvertedScale` will automatically fetch `scaleX` and `scaleY` from the nearest parent.
  2814. * By passing other `MotionValue`s in as `useInvertedScale({ scaleX, scaleY })`, it will invert the output
  2815. * of those instead.
  2816. *
  2817. * ```jsx
  2818. * const MyComponent = () => {
  2819. * const { scaleX, scaleY } = useInvertedScale()
  2820. * return <motion.div style={{ scaleX, scaleY }} />
  2821. * }
  2822. * ```
  2823. *
  2824. * @deprecated
  2825. */
  2826. function useInvertedScale(scale) {
  2827. let parentScaleX = useMotionValue(1);
  2828. let parentScaleY = useMotionValue(1);
  2829. const { visualElement } = React.useContext(create.MotionContext);
  2830. motionUtils.invariant(!!(scale || visualElement), "If no scale values are provided, useInvertedScale must be used within a child of another motion component.");
  2831. motionUtils.warning(hasWarned, "useInvertedScale is deprecated and will be removed in 3.0. Use the layout prop instead.");
  2832. hasWarned = true;
  2833. if (scale) {
  2834. parentScaleX = scale.scaleX || parentScaleX;
  2835. parentScaleY = scale.scaleY || parentScaleY;
  2836. }
  2837. else if (visualElement) {
  2838. parentScaleX = visualElement.getValue("scaleX", 1);
  2839. parentScaleY = visualElement.getValue("scaleY", 1);
  2840. }
  2841. const scaleX = useTransform(parentScaleX, invertScale);
  2842. const scaleY = useTransform(parentScaleY, invertScale);
  2843. return { scaleX, scaleY };
  2844. }
  2845. exports.AcceleratedAnimation = create.AcceleratedAnimation;
  2846. exports.FlatTree = create.FlatTree;
  2847. exports.LayoutGroupContext = create.LayoutGroupContext;
  2848. exports.MotionConfigContext = create.MotionConfigContext;
  2849. exports.MotionContext = create.MotionContext;
  2850. exports.PresenceContext = create.PresenceContext;
  2851. exports.SwitchLayoutGroupContext = create.SwitchLayoutGroupContext;
  2852. exports.VisualElement = create.VisualElement;
  2853. exports.addPointerEvent = create.addPointerEvent;
  2854. exports.addPointerInfo = create.addPointerInfo;
  2855. exports.addScaleCorrector = create.addScaleCorrector;
  2856. exports.animateValue = create.animateValue;
  2857. exports.animateVisualElement = create.animateVisualElement;
  2858. exports.animations = create.animations;
  2859. exports.anticipate = create.anticipate;
  2860. exports.backIn = create.backIn;
  2861. exports.backInOut = create.backInOut;
  2862. exports.backOut = create.backOut;
  2863. exports.buildTransform = create.buildTransform;
  2864. exports.calcLength = create.calcLength;
  2865. exports.circIn = create.circIn;
  2866. exports.circInOut = create.circInOut;
  2867. exports.circOut = create.circOut;
  2868. exports.clamp = create.clamp;
  2869. exports.color = create.color;
  2870. exports.complex = create.complex;
  2871. exports.createBox = create.createBox;
  2872. exports.createRendererMotionComponent = create.createRendererMotionComponent;
  2873. exports.cubicBezier = create.cubicBezier;
  2874. exports.delay = create.delay;
  2875. exports.distance = create.distance;
  2876. exports.distance2D = create.distance2D;
  2877. exports.easeIn = create.easeIn;
  2878. exports.easeInOut = create.easeInOut;
  2879. exports.easeOut = create.easeOut;
  2880. exports.filterProps = create.filterProps;
  2881. exports.findSpring = create.findSpring;
  2882. exports.inertia = create.inertia;
  2883. exports.interpolate = create.interpolate;
  2884. exports.isBrowser = create.isBrowser;
  2885. exports.isMotionValue = create.isMotionValue;
  2886. exports.isValidMotionProp = create.isValidMotionProp;
  2887. exports.keyframes = create.keyframes;
  2888. exports.makeUseVisualState = create.makeUseVisualState;
  2889. exports.mirrorEasing = create.mirrorEasing;
  2890. exports.mix = create.mix;
  2891. exports.optimizedAppearDataAttribute = create.optimizedAppearDataAttribute;
  2892. exports.pipe = create.pipe;
  2893. exports.px = create.px;
  2894. exports.resolveMotionValue = create.resolveMotionValue;
  2895. exports.reverseEasing = create.reverseEasing;
  2896. exports.spring = create.spring;
  2897. exports.useIsPresent = create.useIsPresent;
  2898. exports.useIsomorphicLayoutEffect = create.useIsomorphicLayoutEffect;
  2899. exports.usePresence = create.usePresence;
  2900. exports.visualElementStore = create.visualElementStore;
  2901. Object.defineProperty(exports, "MotionValue", {
  2902. enumerable: true,
  2903. get: function () { return motionDom.MotionValue; }
  2904. });
  2905. Object.defineProperty(exports, "cancelFrame", {
  2906. enumerable: true,
  2907. get: function () { return motionDom.cancelFrame; }
  2908. });
  2909. Object.defineProperty(exports, "cancelSync", {
  2910. enumerable: true,
  2911. get: function () { return motionDom.cancelSync; }
  2912. });
  2913. Object.defineProperty(exports, "frame", {
  2914. enumerable: true,
  2915. get: function () { return motionDom.frame; }
  2916. });
  2917. Object.defineProperty(exports, "frameData", {
  2918. enumerable: true,
  2919. get: function () { return motionDom.frameData; }
  2920. });
  2921. Object.defineProperty(exports, "hover", {
  2922. enumerable: true,
  2923. get: function () { return motionDom.hover; }
  2924. });
  2925. Object.defineProperty(exports, "isDragActive", {
  2926. enumerable: true,
  2927. get: function () { return motionDom.isDragActive; }
  2928. });
  2929. Object.defineProperty(exports, "motionValue", {
  2930. enumerable: true,
  2931. get: function () { return motionDom.motionValue; }
  2932. });
  2933. Object.defineProperty(exports, "press", {
  2934. enumerable: true,
  2935. get: function () { return motionDom.press; }
  2936. });
  2937. Object.defineProperty(exports, "sync", {
  2938. enumerable: true,
  2939. get: function () { return motionDom.sync; }
  2940. });
  2941. Object.defineProperty(exports, "time", {
  2942. enumerable: true,
  2943. get: function () { return motionDom.time; }
  2944. });
  2945. Object.defineProperty(exports, "MotionGlobalConfig", {
  2946. enumerable: true,
  2947. get: function () { return motionUtils.MotionGlobalConfig; }
  2948. });
  2949. Object.defineProperty(exports, "invariant", {
  2950. enumerable: true,
  2951. get: function () { return motionUtils.invariant; }
  2952. });
  2953. Object.defineProperty(exports, "noop", {
  2954. enumerable: true,
  2955. get: function () { return motionUtils.noop; }
  2956. });
  2957. Object.defineProperty(exports, "progress", {
  2958. enumerable: true,
  2959. get: function () { return motionUtils.progress; }
  2960. });
  2961. exports.AnimatePresence = AnimatePresence;
  2962. exports.AnimateSharedLayout = AnimateSharedLayout;
  2963. exports.DeprecatedLayoutGroupContext = DeprecatedLayoutGroupContext;
  2964. exports.DragControls = DragControls;
  2965. exports.LayoutGroup = LayoutGroup;
  2966. exports.LazyMotion = LazyMotion;
  2967. exports.MotionConfig = MotionConfig;
  2968. exports.Reorder = namespace;
  2969. exports.WillChangeMotionValue = WillChangeMotionValue;
  2970. exports.animate = animate;
  2971. exports.animateMini = animateMini;
  2972. exports.animationControls = animationControls;
  2973. exports.createScopedAnimate = createScopedAnimate;
  2974. exports.disableInstantTransitions = disableInstantTransitions;
  2975. exports.domAnimation = domAnimation;
  2976. exports.domMax = domMax;
  2977. exports.domMin = domMin;
  2978. exports.inView = inView;
  2979. exports.isMotionComponent = isMotionComponent;
  2980. exports.m = m;
  2981. exports.motion = motion;
  2982. exports.scroll = scroll;
  2983. exports.scrollInfo = scrollInfo;
  2984. exports.stagger = stagger;
  2985. exports.startOptimizedAppearAnimation = startOptimizedAppearAnimation;
  2986. exports.steps = steps;
  2987. exports.transform = transform;
  2988. exports.unwrapMotionComponent = unwrapMotionComponent;
  2989. exports.useAnimate = useAnimate;
  2990. exports.useAnimateMini = useAnimateMini;
  2991. exports.useAnimation = useAnimation;
  2992. exports.useAnimationControls = useAnimationControls;
  2993. exports.useAnimationFrame = useAnimationFrame;
  2994. exports.useCycle = useCycle;
  2995. exports.useDeprecatedAnimatedState = useAnimatedState;
  2996. exports.useDeprecatedInvertedScale = useInvertedScale;
  2997. exports.useDomEvent = useDomEvent;
  2998. exports.useDragControls = useDragControls;
  2999. exports.useElementScroll = useElementScroll;
  3000. exports.useForceUpdate = useForceUpdate;
  3001. exports.useInView = useInView;
  3002. exports.useInstantLayoutTransition = useInstantLayoutTransition;
  3003. exports.useInstantTransition = useInstantTransition;
  3004. exports.useMotionTemplate = useMotionTemplate;
  3005. exports.useMotionValue = useMotionValue;
  3006. exports.useMotionValueEvent = useMotionValueEvent;
  3007. exports.usePresenceData = usePresenceData;
  3008. exports.useReducedMotion = useReducedMotion;
  3009. exports.useReducedMotionConfig = useReducedMotionConfig;
  3010. exports.useResetProjection = useResetProjection;
  3011. exports.useScroll = useScroll;
  3012. exports.useSpring = useSpring;
  3013. exports.useTime = useTime;
  3014. exports.useTransform = useTransform;
  3015. exports.useUnmountEffect = useUnmountEffect;
  3016. exports.useVelocity = useVelocity;
  3017. exports.useViewportScroll = useViewportScroll;
  3018. exports.useWillChange = useWillChange;
  3019. exports.wrap = wrap;