react-spring-carousel 3.0.0-beta002 → 3.0.0-beta005

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/umd/index.js CHANGED
@@ -1,2 +1,4491 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("@react-spring/web"),require("react"),require("@use-gesture/react"),require("screenfull")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","@react-spring/web","react","@use-gesture/react","screenfull"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactSpringCarousel={},e.ReactJSXRuntime,e.web,e.React,e.UseGestureReact,e.Screenfull)}(this,(function(e,t,r,n,i,c){"use strict";const u="RSC::Event";function o({thumbsSlideAxis:e="x",withThumbs:i=!1,prepareThumbsData:c,items:u}){const o=n.useRef(null),[s,l]=r.useSpring((()=>({val:0})));function a(){var t;return Math.round(Number(null===(t=o.current)||void 0===t?void 0:t["x"===e?"scrollWidth":"scrollHeight"])-o.current.getBoundingClientRect()["x"===e?"width":"height"])}return{thumbsFragment:i?t.jsx("div",Object.assign({className:"use-spring-carousel-thumbs-wrapper",ref:o,onWheel:()=>s.val.stop(),style:Object.assign({display:"flex",flex:"1",position:"relative",width:"100%",height:"100%",flexDirection:"x"===e?"row":"column"},"x"===e?{overflowX:"auto"}:{overflowY:"auto",maxHeight:"100%"})},{children:function(){function e(e){return e.map((e=>({id:e.id,renderThumb:e.renderThumb})))}return c?c(e(u)):e(u)}().map((({id:e,renderThumb:r})=>{const n=`thumb-item-${e}`;return t.jsx("div",Object.assign({id:n,className:"thumb-item"},{children:r}),n)}))})):null,handleScroll:function(t){var r,n;const i=o.current?o.current.querySelector(`#thumb-item-${u[t].id}`):null;if(i&&o.current&&!function(e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}(i)){const t=i.offsetLeft,c=t>a()?a():t;l.start({from:{val:null!==(n=null===(r=o.current)||void 0===r?void 0:r["x"===e?"scrollLeft":"scrollTop"])&&void 0!==n?n:0},to:{val:c},onChange:({value:t})=>{o.current&&(o.current["x"===e?"scrollLeft":"scrollTop"]=Math.abs(t.val))}})}}}}const s=n.createContext(void 0);e.useSpringCarousel=function({items:e,init:s=!0,withThumbs:l,thumbsSlideAxis:a="x",itemsPerSlide:d=1,slideType:f="fixed",gutter:m=0,withLoop:g=!1,startEndGutter:h=0,carouselSlideAxis:v="x",disableGestures:x=!1,draggingSlideTreshold:p,slideWhenThresholdIsReached:b=!1,freeScroll:w,enableFreeScrollDrag:y,initialStartingPosition:E,prepareThumbsData:R,initialActiveItem:T=0}){const j=n.useRef(0),C=n.useRef(null!=p?p:0),I=n.useRef("initial"),S=n.useRef("initial"),O=n.useRef(0),[L,M]=r.useSpring((()=>({val:0,pause:!s,onChange({value:e}){w&&$.current?(te(),"x"===v?$.current.scrollLeft=Math.abs(e.val):$.current.scrollTop=Math.abs(e.val)):W.current&&(W.current.style.transform="x"===v?`translate3d(${e.val}px, 0px,0px)`:`translate3d(0px,${e.val}px,0px)`)}}))),F=n.useRef(T),A=n.useRef(0===T),N=n.useRef(!1),$=n.useRef(null),W=n.useRef(null),q=n.useCallback((()=>g?[...e.map((e=>Object.assign(Object.assign({},e),{id:`prev-repeated-item-${e.id}`}))),...e,...e.map((e=>Object.assign(Object.assign({},e),{id:`next-repeated-item-${e.id}`})))]:[...e]),[e,g])(),{emitEvent:D,useListenToCustomEvent:k}=function(){const e=n.useRef(null);return n.useEffect((()=>{e.current=document.createElement("div")}),[]),{useListenToCustomEvent:function(t){n.useEffect((()=>{function r(e){t(e.detail)}if(e.current)return e.current.addEventListener(u,r,!1),()=>{var t;null===(t=e.current)||void 0===t||t.removeEventListener(u,r,!1)}}),[])},emitEvent:function(t){if(e.current){const r=new CustomEvent(u,{detail:t});e.current.dispatchEvent(r)}}}}(),{thumbsFragment:B,handleScroll:H}=o({withThumbs:!!l,thumbsSlideAxis:a,prepareThumbsData:R,items:e}),{enterFullscreen:z,exitFullscreen:P,getIsFullscreen:G}=function({mainCarouselWrapperRef:e,emitEvent:t,handleResize:r}){const i=n.useRef(!1);function u(e){i.current=e}return n.useEffect((()=>{function e(){document.fullscreenElement&&(u(!0),t({eventName:"onFullscreenChange",isFullscreen:!0}),r&&r()),document.fullscreenElement||(u(!1),t({eventName:"onFullscreenChange",isFullscreen:!1}),r&&r())}if(c.isEnabled)return c.on("change",e),()=>{c.isEnabled&&c.off("change",e)}}),[]),{enterFullscreen:function(t){c.isEnabled&&c.request(t||e.current)},exitFullscreen:function(){c.isEnabled&&c.exit()},getIsFullscreen:function(){return i.current}}}({mainCarouselWrapperRef:$,emitEvent:D,handleResize:()=>K()});function X(){var e;const t=null===(e=$.current)||void 0===e?void 0:e.querySelector(".use-spring-carousel-item");if(!t)throw Error("No carousel items available!");return t.getBoundingClientRect()["x"===v?"width":"height"]+m}function Y({from:t,to:n,nextActiveItem:i,immediate:c=!1,slideMode:u}){S.current=u,"number"==typeof i&&(w||(F.current=i),D({eventName:"onSlideStartChange",slideActionType:I.current,slideMode:S.current,nextItem:{startReached:A.current,endReached:N.current,index:w?-1:F.current,id:w?"":e[F.current].id}})),O.current=n,M.start({immediate:c,from:{val:t},to:{val:n},config:Object.assign(Object.assign({},r.config.default),{velocity:L.val.velocity}),onRest(t){!c&&t.finished&&D({eventName:"onSlideChange",slideActionType:I.current,slideMode:S.current,currentItem:{startReached:A.current,endReached:N.current,index:w?-1:F.current,id:w?"":e[F.current].id}})}}),l&&!c&&H(F.current)}function J(){var t;return g?X()*e.length:Math.round(Number(null===(t=W.current)||void 0===t?void 0:t["x"===v?"scrollWidth":"scrollHeight"])-W.current.getBoundingClientRect()["x"===v?"width":"height"])}function U(){var e;const t=null===(e=W.current)||void 0===e?void 0:e.querySelector(".use-spring-carousel-item");if(!t)throw Error("No carousel items available!");return t.getBoundingClientRect()["x"===v?"width":"height"]+m}function K(){const t="x"===v?"left":"top";function r(e){const r=W.current;r&&(g?(r.style.top="0px",r.style.left="0px",r.style[t]=`-${e-h}px`):(r.style.left="0px",r.style.top="0px"))}const n=Math.abs(Q());if(n<J()&&N.current&&(N.current=!1),n>J()){const e=-J();return N.current=!0,O.current=e,void M.start({immediate:!0,val:e})}if(r("center"===E?U()*e.length-X()*Math.round((d-1)/2):"end"===E?U()*e.length-X()*Math.round(d-1):U()*e.length),!w&&"fixed"===f){const e=-X()*F.current;O.current=e,M.start({immediate:!0,val:e})}}function Q(){return w&&$.current?$.current["x"===v?"scrollLeft":"scrollTop"]:L.val.get()}function V(e,t){if(w&&"next"===e){const e=O.current+X();return e>J()?J():e}if(w&&"prev"===e){const e=O.current-X();return e<0?0:e}return"next"===e?t?-t*X():O.current-X():t?-t*X():O.current+X()}function Z(t="click",r){if(!s||A.current&&!g)return;I.current="prev",N.current=!1;const n=r||F.current-1;if(!g){const e=V("prev",r)+X()/3>0;if(A.current)return;if(e)return A.current=!0,N.current=!1,void Y({slideMode:t,from:Q(),to:0,nextActiveItem:0})}if(g&&A.current)return A.current=!1,N.current=!0,void Y({slideMode:t,from:Q()-X()*e.length,to:-X()*e.length+X(),nextActiveItem:e.length-1});0===n&&(A.current=!0),n!==e.length-1&&-1!==n||(N.current=!0),Y({slideMode:t,from:Q(),to:V("prev",r),nextActiveItem:n})}function _(t="click",r){if(!s||N.current&&!g)return;I.current="next",A.current=!1;const n=r||F.current+1;if(!g){const e=Math.abs(V("next",r))>J()-X()/3;if(N.current)return;if(e)return A.current=!1,N.current=!0,void Y({slideMode:t,from:Q(),to:-J(),nextActiveItem:n})}if(g&&N.current)return N.current=!1,A.current=!0,void Y({slideMode:t,from:Q()+X()*e.length,to:0,nextActiveItem:0});0===n&&(A.current=!0),n===e.length-1&&(N.current=!0),Y({slideMode:t,from:Q(),to:V("next",r),nextActiveItem:n})}n.useEffect((()=>{j.current=window.innerWidth}),[]),n.useEffect((()=>{K()}),[E,d,g,h,m,w,f,s]),n.useLayoutEffect((()=>{W.current&&K()}),[]),n.useEffect((()=>{C.current=p||Math.floor(X()/2/2)}),[p]),n.useEffect((()=>{function e(){window.innerWidth!==j.current&&(j.current=window.innerWidth,K())}return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}}),[]);const ee=i.useDrag((e=>{const t=e.dragging,n=e.offset["x"===v?0:1],i=e.movement["x"===v?0:1],c=e.direction["x"===v?0:1],u=i>C.current,o=i<-C.current;if(t)return I.current=c>0?"prev":"next",D(Object.assign(Object.assign({},e),{eventName:"onDrag",slideActionType:I.current})),w?"prev"===I.current&&n>0?(e.cancel(),void M.start({from:{val:Q()},to:{val:0},config:{velocity:e.velocity,friction:50,tension:1e3}})):void M.start({from:{val:Q()},to:{val:-n},config:{velocity:e.velocity,friction:50,tension:1e3}}):(M.start({val:n,config:{velocity:e.velocity,friction:50,tension:1e3}}),void(b&&o?(_("drag"),e.cancel()):b&&u&&(Z("drag"),e.cancel())));e.last&&!e.canceled&&w&&("prev"===I.current&&Z("drag"),"next"===I.current&&_("drag")),!e.last||e.canceled||w||(o?!g&&N.current?M.start({val:-J(),config:Object.assign(Object.assign({},r.config.default),{velocity:e.velocity})}):_("drag"):u?!g&&A.current?M.start({val:0,config:Object.assign(Object.assign({},r.config.default),{velocity:e.velocity})}):Z("drag"):M.start({val:O.current,config:Object.assign(Object.assign({},r.config.default),{velocity:e.velocity})}))}),{enabled:s&&!x&&!w||!!w&&!!y,axis:v,from:()=>w&&$.current?[-$.current.scrollLeft,-$.current.scrollTop]:[L.val.get(),L.val.get()]});function te(){$.current&&(O.current=$.current["x"===v?"scrollLeft":"scrollTop"],0===$.current["x"===v?"scrollLeft":"scrollTop"]&&(A.current=!0,N.current=!1),$.current["x"===v?"scrollLeft":"scrollTop"]>0&&$.current["x"===v?"scrollLeft":"scrollTop"]<J()&&(A.current=!1,N.current=!1),$.current["x"===v?"scrollLeft":"scrollTop"]===J()&&(A.current=!1,N.current=!0))}function re(t){return e.findIndex((e=>e.id===t))}function ne(t,r){let n=0;if(n="string"==typeof t?e.findIndex((e=>e.id===t)):t,n<0||n>=e.length)throw new Error(r);return n}return{useListenToCustomEvent:k,carouselFragment:t.jsx("div",Object.assign({ref:$},w?{onWheel(){L.val.stop(),te()}}:{},{style:Object.assign({display:"flex",position:"relative",width:"100%",height:"100%"},w?"x"===v?{overflowX:"auto"}:{overflowY:"auto"}:{})},{children:t.jsx("div",Object.assign({ref:W},ee(),{style:Object.assign({position:"relative",display:"flex",flexDirection:"x"===v?"row":"column",touchAction:"none"},function(){const e=`calc(100% - ${2*h}px)`;return{width:"x"===v?e:"100%",height:"y"===v?e:"100%"}}())},{children:q.map(((e,r)=>t.jsx("div",Object.assign({className:"use-spring-carousel-item","data-testid":"use-spring-carousel-item-wrapper",style:Object.assign({display:"flex",position:"relative",flex:"1"},"fixed"!==f||w?Object.assign({marginRight:`${m}px`}):{marginRight:`${m}px`,flex:`1 0 calc(100% / ${d} - ${m*(d-1)/d}px)`})},{children:e.renderItem}),`${e.id}-${r}`)))}))})),enterFullscreen:z,exitFullscreen:P,getIsFullscreen:G,thumbsFragment:B,slideToItem:function(t){if(!s)return;A.current=!1,N.current=!1;const r=ne(t,"The item you want to slide to doesn't exist; please check che item id or the index you're passing to.");if(r===F.current)return;const n=re(e[F.current].id),i=re(e[r].id);i>n?_("click",i):Z("click",i)},getIsNextItem:function(t){const r=re(t),n=F.current;return g&&n===e.length-1?0===r:r===n+1},getIsPrevItem:function(t){const r=re(t),n=F.current;return g&&0===n?r===e.length-1:r===n-1},slideToPrevItem:()=>Z(),slideToNextItem:()=>_(),getIsActiveItem:e=>ne(e,"The item you want to check doesn't exist")===F.current}},e.useSpringCarouselContext=function(){const e=n.useContext(s);if(!e)throw new Error("useSpringCarouselContext must be used within the carousel.");return e}}));
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react/jsx-runtime'), require('react'), require('react-dom'), require('@use-gesture/react'), require('screenfull')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'react/jsx-runtime', 'react', 'react-dom', '@use-gesture/react', 'screenfull'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactSpringCarousel = {}, global.ReactJSXRuntime, global.React, global.ReactDOM, global.UseGestureReact, global.Screenfull));
5
+ })(this, (function (exports, jsxRuntime, React, reactDom, react, screenfull) { 'use strict';
6
+
7
+ function _interopNamespaceDefault(e) {
8
+ var n = Object.create(null);
9
+ if (e) {
10
+ Object.keys(e).forEach(function (k) {
11
+ if (k !== 'default') {
12
+ var d = Object.getOwnPropertyDescriptor(e, k);
13
+ Object.defineProperty(n, k, d.get ? d : {
14
+ enumerable: true,
15
+ get: function () { return e[k]; }
16
+ });
17
+ }
18
+ });
19
+ }
20
+ n.default = e;
21
+ return Object.freeze(n);
22
+ }
23
+
24
+ var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
25
+
26
+ let updateQueue = makeQueue();
27
+ const raf = fn => schedule(fn, updateQueue);
28
+ let writeQueue = makeQueue();
29
+
30
+ raf.write = fn => schedule(fn, writeQueue);
31
+
32
+ let onStartQueue = makeQueue();
33
+
34
+ raf.onStart = fn => schedule(fn, onStartQueue);
35
+
36
+ let onFrameQueue = makeQueue();
37
+
38
+ raf.onFrame = fn => schedule(fn, onFrameQueue);
39
+
40
+ let onFinishQueue = makeQueue();
41
+
42
+ raf.onFinish = fn => schedule(fn, onFinishQueue);
43
+
44
+ let timeouts = [];
45
+
46
+ raf.setTimeout = (handler, ms) => {
47
+ let time = raf.now() + ms;
48
+
49
+ let cancel = () => {
50
+ let i = timeouts.findIndex(t => t.cancel == cancel);
51
+ if (~i) timeouts.splice(i, 1);
52
+ pendingCount -= ~i ? 1 : 0;
53
+ };
54
+
55
+ let timeout = {
56
+ time,
57
+ handler,
58
+ cancel
59
+ };
60
+ timeouts.splice(findTimeout(time), 0, timeout);
61
+ pendingCount += 1;
62
+ start();
63
+ return timeout;
64
+ };
65
+
66
+ let findTimeout = time => ~(~timeouts.findIndex(t => t.time > time) || ~timeouts.length);
67
+
68
+ raf.cancel = fn => {
69
+ onStartQueue.delete(fn);
70
+ onFrameQueue.delete(fn);
71
+ onFinishQueue.delete(fn);
72
+ updateQueue.delete(fn);
73
+ writeQueue.delete(fn);
74
+ };
75
+
76
+ raf.sync = fn => {
77
+ sync = true;
78
+ raf.batchedUpdates(fn);
79
+ sync = false;
80
+ };
81
+
82
+ raf.throttle = fn => {
83
+ let lastArgs;
84
+
85
+ function queuedFn() {
86
+ try {
87
+ fn(...lastArgs);
88
+ } finally {
89
+ lastArgs = null;
90
+ }
91
+ }
92
+
93
+ function throttled(...args) {
94
+ lastArgs = args;
95
+ raf.onStart(queuedFn);
96
+ }
97
+
98
+ throttled.handler = fn;
99
+
100
+ throttled.cancel = () => {
101
+ onStartQueue.delete(queuedFn);
102
+ lastArgs = null;
103
+ };
104
+
105
+ return throttled;
106
+ };
107
+
108
+ let nativeRaf = typeof window != 'undefined' ? window.requestAnimationFrame : () => {};
109
+
110
+ raf.use = impl => nativeRaf = impl;
111
+
112
+ raf.now = typeof performance != 'undefined' ? () => performance.now() : Date.now;
113
+
114
+ raf.batchedUpdates = fn => fn();
115
+
116
+ raf.catch = console.error;
117
+ raf.frameLoop = 'always';
118
+
119
+ raf.advance = () => {
120
+ if (raf.frameLoop !== 'demand') {
121
+ console.warn('Cannot call the manual advancement of rafz whilst frameLoop is not set as demand');
122
+ } else {
123
+ update();
124
+ }
125
+ };
126
+
127
+ let ts = -1;
128
+ let pendingCount = 0;
129
+ let sync = false;
130
+
131
+ function schedule(fn, queue) {
132
+ if (sync) {
133
+ queue.delete(fn);
134
+ fn(0);
135
+ } else {
136
+ queue.add(fn);
137
+ start();
138
+ }
139
+ }
140
+
141
+ function start() {
142
+ if (ts < 0) {
143
+ ts = 0;
144
+
145
+ if (raf.frameLoop !== 'demand') {
146
+ nativeRaf(loop);
147
+ }
148
+ }
149
+ }
150
+
151
+ function stop() {
152
+ ts = -1;
153
+ }
154
+
155
+ function loop() {
156
+ if (~ts) {
157
+ nativeRaf(loop);
158
+ raf.batchedUpdates(update);
159
+ }
160
+ }
161
+
162
+ function update() {
163
+ let prevTs = ts;
164
+ ts = raf.now();
165
+ let count = findTimeout(ts);
166
+
167
+ if (count) {
168
+ eachSafely(timeouts.splice(0, count), t => t.handler());
169
+ pendingCount -= count;
170
+ }
171
+
172
+ if (!pendingCount) {
173
+ stop();
174
+ return;
175
+ }
176
+
177
+ onStartQueue.flush();
178
+ updateQueue.flush(prevTs ? Math.min(64, ts - prevTs) : 16.667);
179
+ onFrameQueue.flush();
180
+ writeQueue.flush();
181
+ onFinishQueue.flush();
182
+ }
183
+
184
+ function makeQueue() {
185
+ let next = new Set();
186
+ let current = next;
187
+ return {
188
+ add(fn) {
189
+ pendingCount += current == next && !next.has(fn) ? 1 : 0;
190
+ next.add(fn);
191
+ },
192
+
193
+ delete(fn) {
194
+ pendingCount -= current == next && next.has(fn) ? 1 : 0;
195
+ return next.delete(fn);
196
+ },
197
+
198
+ flush(arg) {
199
+ if (current.size) {
200
+ next = new Set();
201
+ pendingCount -= current.size;
202
+ eachSafely(current, fn => fn(arg) && next.add(fn));
203
+ pendingCount += next.size;
204
+ current = next;
205
+ }
206
+ }
207
+
208
+ };
209
+ }
210
+
211
+ function eachSafely(values, each) {
212
+ values.forEach(value => {
213
+ try {
214
+ each(value);
215
+ } catch (e) {
216
+ raf.catch(e);
217
+ }
218
+ });
219
+ }
220
+
221
+ function noop() {}
222
+ const defineHidden = (obj, key, value) => Object.defineProperty(obj, key, {
223
+ value,
224
+ writable: true,
225
+ configurable: true
226
+ });
227
+ const is = {
228
+ arr: Array.isArray,
229
+ obj: a => !!a && a.constructor.name === 'Object',
230
+ fun: a => typeof a === 'function',
231
+ str: a => typeof a === 'string',
232
+ num: a => typeof a === 'number',
233
+ und: a => a === undefined
234
+ };
235
+ function isEqual(a, b) {
236
+ if (is.arr(a)) {
237
+ if (!is.arr(b) || a.length !== b.length) return false;
238
+
239
+ for (let i = 0; i < a.length; i++) {
240
+ if (a[i] !== b[i]) return false;
241
+ }
242
+
243
+ return true;
244
+ }
245
+
246
+ return a === b;
247
+ }
248
+ const each = (obj, fn) => obj.forEach(fn);
249
+ function eachProp(obj, fn, ctx) {
250
+ if (is.arr(obj)) {
251
+ for (let i = 0; i < obj.length; i++) {
252
+ fn.call(ctx, obj[i], `${i}`);
253
+ }
254
+
255
+ return;
256
+ }
257
+
258
+ for (const key in obj) {
259
+ if (obj.hasOwnProperty(key)) {
260
+ fn.call(ctx, obj[key], key);
261
+ }
262
+ }
263
+ }
264
+ const toArray = a => is.und(a) ? [] : is.arr(a) ? a : [a];
265
+ function flush(queue, iterator) {
266
+ if (queue.size) {
267
+ const items = Array.from(queue);
268
+ queue.clear();
269
+ each(items, iterator);
270
+ }
271
+ }
272
+ const flushCalls = (queue, ...args) => flush(queue, fn => fn(...args));
273
+ const isSSR = () => typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent);
274
+
275
+ let createStringInterpolator$1;
276
+ let to;
277
+ let colors$1 = null;
278
+ let skipAnimation = false;
279
+ let willAdvance = noop;
280
+ const assign = globals => {
281
+ if (globals.to) to = globals.to;
282
+ if (globals.now) raf.now = globals.now;
283
+ if (globals.colors !== undefined) colors$1 = globals.colors;
284
+ if (globals.skipAnimation != null) skipAnimation = globals.skipAnimation;
285
+ if (globals.createStringInterpolator) createStringInterpolator$1 = globals.createStringInterpolator;
286
+ if (globals.requestAnimationFrame) raf.use(globals.requestAnimationFrame);
287
+ if (globals.batchedUpdates) raf.batchedUpdates = globals.batchedUpdates;
288
+ if (globals.willAdvance) willAdvance = globals.willAdvance;
289
+ if (globals.frameLoop) raf.frameLoop = globals.frameLoop;
290
+ };
291
+
292
+ var globals = /*#__PURE__*/Object.freeze({
293
+ __proto__: null,
294
+ get createStringInterpolator () { return createStringInterpolator$1; },
295
+ get to () { return to; },
296
+ get colors () { return colors$1; },
297
+ get skipAnimation () { return skipAnimation; },
298
+ get willAdvance () { return willAdvance; },
299
+ assign: assign
300
+ });
301
+
302
+ const startQueue = new Set();
303
+ let currentFrame = [];
304
+ let prevFrame = [];
305
+ let priority = 0;
306
+ const frameLoop = {
307
+ get idle() {
308
+ return !startQueue.size && !currentFrame.length;
309
+ },
310
+
311
+ start(animation) {
312
+ if (priority > animation.priority) {
313
+ startQueue.add(animation);
314
+ raf.onStart(flushStartQueue);
315
+ } else {
316
+ startSafely(animation);
317
+ raf(advance);
318
+ }
319
+ },
320
+
321
+ advance,
322
+
323
+ sort(animation) {
324
+ if (priority) {
325
+ raf.onFrame(() => frameLoop.sort(animation));
326
+ } else {
327
+ const prevIndex = currentFrame.indexOf(animation);
328
+
329
+ if (~prevIndex) {
330
+ currentFrame.splice(prevIndex, 1);
331
+ startUnsafely(animation);
332
+ }
333
+ }
334
+ },
335
+
336
+ clear() {
337
+ currentFrame = [];
338
+ startQueue.clear();
339
+ }
340
+
341
+ };
342
+
343
+ function flushStartQueue() {
344
+ startQueue.forEach(startSafely);
345
+ startQueue.clear();
346
+ raf(advance);
347
+ }
348
+
349
+ function startSafely(animation) {
350
+ if (!currentFrame.includes(animation)) startUnsafely(animation);
351
+ }
352
+
353
+ function startUnsafely(animation) {
354
+ currentFrame.splice(findIndex(currentFrame, other => other.priority > animation.priority), 0, animation);
355
+ }
356
+
357
+ function advance(dt) {
358
+ const nextFrame = prevFrame;
359
+
360
+ for (let i = 0; i < currentFrame.length; i++) {
361
+ const animation = currentFrame[i];
362
+ priority = animation.priority;
363
+
364
+ if (!animation.idle) {
365
+ willAdvance(animation);
366
+ animation.advance(dt);
367
+
368
+ if (!animation.idle) {
369
+ nextFrame.push(animation);
370
+ }
371
+ }
372
+ }
373
+
374
+ priority = 0;
375
+ prevFrame = currentFrame;
376
+ prevFrame.length = 0;
377
+ currentFrame = nextFrame;
378
+ return currentFrame.length > 0;
379
+ }
380
+
381
+ function findIndex(arr, test) {
382
+ const index = arr.findIndex(test);
383
+ return index < 0 ? arr.length : index;
384
+ }
385
+
386
+ const colors = {
387
+ transparent: 0x00000000,
388
+ aliceblue: 0xf0f8ffff,
389
+ antiquewhite: 0xfaebd7ff,
390
+ aqua: 0x00ffffff,
391
+ aquamarine: 0x7fffd4ff,
392
+ azure: 0xf0ffffff,
393
+ beige: 0xf5f5dcff,
394
+ bisque: 0xffe4c4ff,
395
+ black: 0x000000ff,
396
+ blanchedalmond: 0xffebcdff,
397
+ blue: 0x0000ffff,
398
+ blueviolet: 0x8a2be2ff,
399
+ brown: 0xa52a2aff,
400
+ burlywood: 0xdeb887ff,
401
+ burntsienna: 0xea7e5dff,
402
+ cadetblue: 0x5f9ea0ff,
403
+ chartreuse: 0x7fff00ff,
404
+ chocolate: 0xd2691eff,
405
+ coral: 0xff7f50ff,
406
+ cornflowerblue: 0x6495edff,
407
+ cornsilk: 0xfff8dcff,
408
+ crimson: 0xdc143cff,
409
+ cyan: 0x00ffffff,
410
+ darkblue: 0x00008bff,
411
+ darkcyan: 0x008b8bff,
412
+ darkgoldenrod: 0xb8860bff,
413
+ darkgray: 0xa9a9a9ff,
414
+ darkgreen: 0x006400ff,
415
+ darkgrey: 0xa9a9a9ff,
416
+ darkkhaki: 0xbdb76bff,
417
+ darkmagenta: 0x8b008bff,
418
+ darkolivegreen: 0x556b2fff,
419
+ darkorange: 0xff8c00ff,
420
+ darkorchid: 0x9932ccff,
421
+ darkred: 0x8b0000ff,
422
+ darksalmon: 0xe9967aff,
423
+ darkseagreen: 0x8fbc8fff,
424
+ darkslateblue: 0x483d8bff,
425
+ darkslategray: 0x2f4f4fff,
426
+ darkslategrey: 0x2f4f4fff,
427
+ darkturquoise: 0x00ced1ff,
428
+ darkviolet: 0x9400d3ff,
429
+ deeppink: 0xff1493ff,
430
+ deepskyblue: 0x00bfffff,
431
+ dimgray: 0x696969ff,
432
+ dimgrey: 0x696969ff,
433
+ dodgerblue: 0x1e90ffff,
434
+ firebrick: 0xb22222ff,
435
+ floralwhite: 0xfffaf0ff,
436
+ forestgreen: 0x228b22ff,
437
+ fuchsia: 0xff00ffff,
438
+ gainsboro: 0xdcdcdcff,
439
+ ghostwhite: 0xf8f8ffff,
440
+ gold: 0xffd700ff,
441
+ goldenrod: 0xdaa520ff,
442
+ gray: 0x808080ff,
443
+ green: 0x008000ff,
444
+ greenyellow: 0xadff2fff,
445
+ grey: 0x808080ff,
446
+ honeydew: 0xf0fff0ff,
447
+ hotpink: 0xff69b4ff,
448
+ indianred: 0xcd5c5cff,
449
+ indigo: 0x4b0082ff,
450
+ ivory: 0xfffff0ff,
451
+ khaki: 0xf0e68cff,
452
+ lavender: 0xe6e6faff,
453
+ lavenderblush: 0xfff0f5ff,
454
+ lawngreen: 0x7cfc00ff,
455
+ lemonchiffon: 0xfffacdff,
456
+ lightblue: 0xadd8e6ff,
457
+ lightcoral: 0xf08080ff,
458
+ lightcyan: 0xe0ffffff,
459
+ lightgoldenrodyellow: 0xfafad2ff,
460
+ lightgray: 0xd3d3d3ff,
461
+ lightgreen: 0x90ee90ff,
462
+ lightgrey: 0xd3d3d3ff,
463
+ lightpink: 0xffb6c1ff,
464
+ lightsalmon: 0xffa07aff,
465
+ lightseagreen: 0x20b2aaff,
466
+ lightskyblue: 0x87cefaff,
467
+ lightslategray: 0x778899ff,
468
+ lightslategrey: 0x778899ff,
469
+ lightsteelblue: 0xb0c4deff,
470
+ lightyellow: 0xffffe0ff,
471
+ lime: 0x00ff00ff,
472
+ limegreen: 0x32cd32ff,
473
+ linen: 0xfaf0e6ff,
474
+ magenta: 0xff00ffff,
475
+ maroon: 0x800000ff,
476
+ mediumaquamarine: 0x66cdaaff,
477
+ mediumblue: 0x0000cdff,
478
+ mediumorchid: 0xba55d3ff,
479
+ mediumpurple: 0x9370dbff,
480
+ mediumseagreen: 0x3cb371ff,
481
+ mediumslateblue: 0x7b68eeff,
482
+ mediumspringgreen: 0x00fa9aff,
483
+ mediumturquoise: 0x48d1ccff,
484
+ mediumvioletred: 0xc71585ff,
485
+ midnightblue: 0x191970ff,
486
+ mintcream: 0xf5fffaff,
487
+ mistyrose: 0xffe4e1ff,
488
+ moccasin: 0xffe4b5ff,
489
+ navajowhite: 0xffdeadff,
490
+ navy: 0x000080ff,
491
+ oldlace: 0xfdf5e6ff,
492
+ olive: 0x808000ff,
493
+ olivedrab: 0x6b8e23ff,
494
+ orange: 0xffa500ff,
495
+ orangered: 0xff4500ff,
496
+ orchid: 0xda70d6ff,
497
+ palegoldenrod: 0xeee8aaff,
498
+ palegreen: 0x98fb98ff,
499
+ paleturquoise: 0xafeeeeff,
500
+ palevioletred: 0xdb7093ff,
501
+ papayawhip: 0xffefd5ff,
502
+ peachpuff: 0xffdab9ff,
503
+ peru: 0xcd853fff,
504
+ pink: 0xffc0cbff,
505
+ plum: 0xdda0ddff,
506
+ powderblue: 0xb0e0e6ff,
507
+ purple: 0x800080ff,
508
+ rebeccapurple: 0x663399ff,
509
+ red: 0xff0000ff,
510
+ rosybrown: 0xbc8f8fff,
511
+ royalblue: 0x4169e1ff,
512
+ saddlebrown: 0x8b4513ff,
513
+ salmon: 0xfa8072ff,
514
+ sandybrown: 0xf4a460ff,
515
+ seagreen: 0x2e8b57ff,
516
+ seashell: 0xfff5eeff,
517
+ sienna: 0xa0522dff,
518
+ silver: 0xc0c0c0ff,
519
+ skyblue: 0x87ceebff,
520
+ slateblue: 0x6a5acdff,
521
+ slategray: 0x708090ff,
522
+ slategrey: 0x708090ff,
523
+ snow: 0xfffafaff,
524
+ springgreen: 0x00ff7fff,
525
+ steelblue: 0x4682b4ff,
526
+ tan: 0xd2b48cff,
527
+ teal: 0x008080ff,
528
+ thistle: 0xd8bfd8ff,
529
+ tomato: 0xff6347ff,
530
+ turquoise: 0x40e0d0ff,
531
+ violet: 0xee82eeff,
532
+ wheat: 0xf5deb3ff,
533
+ white: 0xffffffff,
534
+ whitesmoke: 0xf5f5f5ff,
535
+ yellow: 0xffff00ff,
536
+ yellowgreen: 0x9acd32ff
537
+ };
538
+
539
+ const NUMBER = '[-+]?\\d*\\.?\\d+';
540
+ const PERCENTAGE = NUMBER + '%';
541
+
542
+ function call(...parts) {
543
+ return '\\(\\s*(' + parts.join(')\\s*,\\s*(') + ')\\s*\\)';
544
+ }
545
+
546
+ const rgb = new RegExp('rgb' + call(NUMBER, NUMBER, NUMBER));
547
+ const rgba = new RegExp('rgba' + call(NUMBER, NUMBER, NUMBER, NUMBER));
548
+ const hsl = new RegExp('hsl' + call(NUMBER, PERCENTAGE, PERCENTAGE));
549
+ const hsla = new RegExp('hsla' + call(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER));
550
+ const hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
551
+ const hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
552
+ const hex6 = /^#([0-9a-fA-F]{6})$/;
553
+ const hex8 = /^#([0-9a-fA-F]{8})$/;
554
+
555
+ function normalizeColor(color) {
556
+ let match;
557
+
558
+ if (typeof color === 'number') {
559
+ return color >>> 0 === color && color >= 0 && color <= 0xffffffff ? color : null;
560
+ }
561
+
562
+ if (match = hex6.exec(color)) return parseInt(match[1] + 'ff', 16) >>> 0;
563
+
564
+ if (colors$1 && colors$1[color] !== undefined) {
565
+ return colors$1[color];
566
+ }
567
+
568
+ if (match = rgb.exec(color)) {
569
+ return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | 0x000000ff) >>> 0;
570
+ }
571
+
572
+ if (match = rgba.exec(color)) {
573
+ return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | parse1(match[4])) >>> 0;
574
+ }
575
+
576
+ if (match = hex3.exec(color)) {
577
+ return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + 'ff', 16) >>> 0;
578
+ }
579
+
580
+ if (match = hex8.exec(color)) return parseInt(match[1], 16) >>> 0;
581
+
582
+ if (match = hex4.exec(color)) {
583
+ return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + match[4] + match[4], 16) >>> 0;
584
+ }
585
+
586
+ if (match = hsl.exec(color)) {
587
+ return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | 0x000000ff) >>> 0;
588
+ }
589
+
590
+ if (match = hsla.exec(color)) {
591
+ return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | parse1(match[4])) >>> 0;
592
+ }
593
+
594
+ return null;
595
+ }
596
+
597
+ function hue2rgb(p, q, t) {
598
+ if (t < 0) t += 1;
599
+ if (t > 1) t -= 1;
600
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
601
+ if (t < 1 / 2) return q;
602
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
603
+ return p;
604
+ }
605
+
606
+ function hslToRgb(h, s, l) {
607
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
608
+ const p = 2 * l - q;
609
+ const r = hue2rgb(p, q, h + 1 / 3);
610
+ const g = hue2rgb(p, q, h);
611
+ const b = hue2rgb(p, q, h - 1 / 3);
612
+ return Math.round(r * 255) << 24 | Math.round(g * 255) << 16 | Math.round(b * 255) << 8;
613
+ }
614
+
615
+ function parse255(str) {
616
+ const int = parseInt(str, 10);
617
+ if (int < 0) return 0;
618
+ if (int > 255) return 255;
619
+ return int;
620
+ }
621
+
622
+ function parse360(str) {
623
+ const int = parseFloat(str);
624
+ return (int % 360 + 360) % 360 / 360;
625
+ }
626
+
627
+ function parse1(str) {
628
+ const num = parseFloat(str);
629
+ if (num < 0) return 0;
630
+ if (num > 1) return 255;
631
+ return Math.round(num * 255);
632
+ }
633
+
634
+ function parsePercentage(str) {
635
+ const int = parseFloat(str);
636
+ if (int < 0) return 0;
637
+ if (int > 100) return 1;
638
+ return int / 100;
639
+ }
640
+
641
+ function colorToRgba(input) {
642
+ let int32Color = normalizeColor(input);
643
+ if (int32Color === null) return input;
644
+ int32Color = int32Color || 0;
645
+ let r = (int32Color & 0xff000000) >>> 24;
646
+ let g = (int32Color & 0x00ff0000) >>> 16;
647
+ let b = (int32Color & 0x0000ff00) >>> 8;
648
+ let a = (int32Color & 0x000000ff) / 255;
649
+ return `rgba(${r}, ${g}, ${b}, ${a})`;
650
+ }
651
+
652
+ const createInterpolator = (range, output, extrapolate) => {
653
+ if (is.fun(range)) {
654
+ return range;
655
+ }
656
+
657
+ if (is.arr(range)) {
658
+ return createInterpolator({
659
+ range,
660
+ output: output,
661
+ extrapolate
662
+ });
663
+ }
664
+
665
+ if (is.str(range.output[0])) {
666
+ return createStringInterpolator$1(range);
667
+ }
668
+
669
+ const config = range;
670
+ const outputRange = config.output;
671
+ const inputRange = config.range || [0, 1];
672
+ const extrapolateLeft = config.extrapolateLeft || config.extrapolate || 'extend';
673
+ const extrapolateRight = config.extrapolateRight || config.extrapolate || 'extend';
674
+
675
+ const easing = config.easing || (t => t);
676
+
677
+ return input => {
678
+ const range = findRange(input, inputRange);
679
+ return interpolate(input, inputRange[range], inputRange[range + 1], outputRange[range], outputRange[range + 1], easing, extrapolateLeft, extrapolateRight, config.map);
680
+ };
681
+ };
682
+
683
+ function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) {
684
+ let result = map ? map(input) : input;
685
+
686
+ if (result < inputMin) {
687
+ if (extrapolateLeft === 'identity') return result;else if (extrapolateLeft === 'clamp') result = inputMin;
688
+ }
689
+
690
+ if (result > inputMax) {
691
+ if (extrapolateRight === 'identity') return result;else if (extrapolateRight === 'clamp') result = inputMax;
692
+ }
693
+
694
+ if (outputMin === outputMax) return outputMin;
695
+ if (inputMin === inputMax) return input <= inputMin ? outputMin : outputMax;
696
+ if (inputMin === -Infinity) result = -result;else if (inputMax === Infinity) result = result - inputMin;else result = (result - inputMin) / (inputMax - inputMin);
697
+ result = easing(result);
698
+ if (outputMin === -Infinity) result = -result;else if (outputMax === Infinity) result = result + outputMin;else result = result * (outputMax - outputMin) + outputMin;
699
+ return result;
700
+ }
701
+
702
+ function findRange(input, inputRange) {
703
+ for (var i = 1; i < inputRange.length - 1; ++i) if (inputRange[i] >= input) break;
704
+
705
+ return i - 1;
706
+ }
707
+
708
+ function _extends$2() {
709
+ _extends$2 = Object.assign ? Object.assign.bind() : function (target) {
710
+ for (var i = 1; i < arguments.length; i++) {
711
+ var source = arguments[i];
712
+
713
+ for (var key in source) {
714
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
715
+ target[key] = source[key];
716
+ }
717
+ }
718
+ }
719
+
720
+ return target;
721
+ };
722
+ return _extends$2.apply(this, arguments);
723
+ }
724
+
725
+ const $get = Symbol.for('FluidValue.get');
726
+ const $observers = Symbol.for('FluidValue.observers');
727
+
728
+ const hasFluidValue = arg => Boolean(arg && arg[$get]);
729
+
730
+ const getFluidValue = arg => arg && arg[$get] ? arg[$get]() : arg;
731
+
732
+ const getFluidObservers = target => target[$observers] || null;
733
+
734
+ function callFluidObserver(observer, event) {
735
+ if (observer.eventObserved) {
736
+ observer.eventObserved(event);
737
+ } else {
738
+ observer(event);
739
+ }
740
+ }
741
+
742
+ function callFluidObservers(target, event) {
743
+ let observers = target[$observers];
744
+
745
+ if (observers) {
746
+ observers.forEach(observer => {
747
+ callFluidObserver(observer, event);
748
+ });
749
+ }
750
+ }
751
+
752
+ class FluidValue {
753
+ constructor(get) {
754
+ this[$get] = void 0;
755
+ this[$observers] = void 0;
756
+
757
+ if (!get && !(get = this.get)) {
758
+ throw Error('Unknown getter');
759
+ }
760
+
761
+ setFluidGetter(this, get);
762
+ }
763
+
764
+ }
765
+
766
+ const setFluidGetter = (target, get) => setHidden(target, $get, get);
767
+
768
+ function addFluidObserver(target, observer) {
769
+ if (target[$get]) {
770
+ let observers = target[$observers];
771
+
772
+ if (!observers) {
773
+ setHidden(target, $observers, observers = new Set());
774
+ }
775
+
776
+ if (!observers.has(observer)) {
777
+ observers.add(observer);
778
+
779
+ if (target.observerAdded) {
780
+ target.observerAdded(observers.size, observer);
781
+ }
782
+ }
783
+ }
784
+
785
+ return observer;
786
+ }
787
+
788
+ function removeFluidObserver(target, observer) {
789
+ let observers = target[$observers];
790
+
791
+ if (observers && observers.has(observer)) {
792
+ const count = observers.size - 1;
793
+
794
+ if (count) {
795
+ observers.delete(observer);
796
+ } else {
797
+ target[$observers] = null;
798
+ }
799
+
800
+ if (target.observerRemoved) {
801
+ target.observerRemoved(count, observer);
802
+ }
803
+ }
804
+ }
805
+
806
+ const setHidden = (target, key, value) => Object.defineProperty(target, key, {
807
+ value,
808
+ writable: true,
809
+ configurable: true
810
+ });
811
+
812
+ const numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
813
+ const colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi;
814
+ const unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, 'i');
815
+ const rgbaRegex = /rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi;
816
+ const cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;
817
+
818
+ const variableToRgba = input => {
819
+ const [token, fallback] = parseCSSVariable(input);
820
+
821
+ if (!token || isSSR()) {
822
+ return input;
823
+ }
824
+
825
+ const value = window.getComputedStyle(document.documentElement).getPropertyValue(token);
826
+
827
+ if (value) {
828
+ return value.trim();
829
+ } else if (fallback && fallback.startsWith('--')) {
830
+ const _value = window.getComputedStyle(document.documentElement).getPropertyValue(fallback);
831
+
832
+ if (_value) {
833
+ return _value;
834
+ } else {
835
+ return input;
836
+ }
837
+ } else if (fallback && cssVariableRegex.test(fallback)) {
838
+ return variableToRgba(fallback);
839
+ } else if (fallback) {
840
+ return fallback;
841
+ }
842
+
843
+ return input;
844
+ };
845
+
846
+ const parseCSSVariable = current => {
847
+ const match = cssVariableRegex.exec(current);
848
+ if (!match) return [,];
849
+ const [, token, fallback] = match;
850
+ return [token, fallback];
851
+ };
852
+
853
+ let namedColorRegex;
854
+
855
+ const rgbaRound = (_, p1, p2, p3, p4) => `rgba(${Math.round(p1)}, ${Math.round(p2)}, ${Math.round(p3)}, ${p4})`;
856
+
857
+ const createStringInterpolator = config => {
858
+ if (!namedColorRegex) namedColorRegex = colors$1 ? new RegExp(`(${Object.keys(colors$1).join('|')})(?!\\w)`, 'g') : /^\b$/;
859
+ const output = config.output.map(value => {
860
+ return getFluidValue(value).replace(cssVariableRegex, variableToRgba).replace(colorRegex, colorToRgba).replace(namedColorRegex, colorToRgba);
861
+ });
862
+ const keyframes = output.map(value => value.match(numberRegex).map(Number));
863
+ const outputRanges = keyframes[0].map((_, i) => keyframes.map(values => {
864
+ if (!(i in values)) {
865
+ throw Error('The arity of each "output" value must be equal');
866
+ }
867
+
868
+ return values[i];
869
+ }));
870
+ const interpolators = outputRanges.map(output => createInterpolator(_extends$2({}, config, {
871
+ output
872
+ })));
873
+ return input => {
874
+ var _output$find;
875
+
876
+ const missingUnit = !unitRegex.test(output[0]) && ((_output$find = output.find(value => unitRegex.test(value))) == null ? void 0 : _output$find.replace(numberRegex, ''));
877
+ let i = 0;
878
+ return output[0].replace(numberRegex, () => `${interpolators[i++](input)}${missingUnit || ''}`).replace(rgbaRegex, rgbaRound);
879
+ };
880
+ };
881
+
882
+ const prefix = 'react-spring: ';
883
+
884
+ const once = fn => {
885
+ const func = fn;
886
+ let called = false;
887
+
888
+ if (typeof func != 'function') {
889
+ throw new TypeError(`${prefix}once requires a function parameter`);
890
+ }
891
+
892
+ return (...args) => {
893
+ if (!called) {
894
+ func(...args);
895
+ called = true;
896
+ }
897
+ };
898
+ };
899
+
900
+ const warnInterpolate = once(console.warn);
901
+ function deprecateInterpolate() {
902
+ warnInterpolate(`${prefix}The "interpolate" function is deprecated in v9 (use "to" instead)`);
903
+ }
904
+ const warnDirectCall = once(console.warn);
905
+ function deprecateDirectCall() {
906
+ warnDirectCall(`${prefix}Directly calling start instead of using the api object is deprecated in v9 (use ".start" instead), this will be removed in later 0.X.0 versions`);
907
+ }
908
+
909
+ function isAnimatedString(value) {
910
+ return is.str(value) && (value[0] == '#' || /\d/.test(value) || !isSSR() && cssVariableRegex.test(value) || value in (colors$1 || {}));
911
+ }
912
+
913
+ const useIsomorphicLayoutEffect = isSSR() ? React.useEffect : React.useLayoutEffect;
914
+
915
+ const useIsMounted = () => {
916
+ const isMounted = React.useRef(false);
917
+ useIsomorphicLayoutEffect(() => {
918
+ isMounted.current = true;
919
+ return () => {
920
+ isMounted.current = false;
921
+ };
922
+ }, []);
923
+ return isMounted;
924
+ };
925
+
926
+ function useForceUpdate() {
927
+ const update = React.useState()[1];
928
+ const isMounted = useIsMounted();
929
+ return () => {
930
+ if (isMounted.current) {
931
+ update(Math.random());
932
+ }
933
+ };
934
+ }
935
+
936
+ function useMemoOne(getResult, inputs) {
937
+ const [initial] = React.useState(() => ({
938
+ inputs,
939
+ result: getResult()
940
+ }));
941
+ const committed = React.useRef();
942
+ const prevCache = committed.current;
943
+ let cache = prevCache;
944
+
945
+ if (cache) {
946
+ const useCache = Boolean(inputs && cache.inputs && areInputsEqual(inputs, cache.inputs));
947
+
948
+ if (!useCache) {
949
+ cache = {
950
+ inputs,
951
+ result: getResult()
952
+ };
953
+ }
954
+ } else {
955
+ cache = initial;
956
+ }
957
+
958
+ React.useEffect(() => {
959
+ committed.current = cache;
960
+
961
+ if (prevCache == initial) {
962
+ initial.inputs = initial.result = undefined;
963
+ }
964
+ }, [cache]);
965
+ return cache.result;
966
+ }
967
+
968
+ function areInputsEqual(next, prev) {
969
+ if (next.length !== prev.length) {
970
+ return false;
971
+ }
972
+
973
+ for (let i = 0; i < next.length; i++) {
974
+ if (next[i] !== prev[i]) {
975
+ return false;
976
+ }
977
+ }
978
+
979
+ return true;
980
+ }
981
+
982
+ const useOnce = effect => React.useEffect(effect, emptyDeps);
983
+ const emptyDeps = [];
984
+
985
+ function usePrev(value) {
986
+ const prevRef = React.useRef();
987
+ React.useEffect(() => {
988
+ prevRef.current = value;
989
+ });
990
+ return prevRef.current;
991
+ }
992
+
993
+ const $node = Symbol.for('Animated:node');
994
+ const isAnimated = value => !!value && value[$node] === value;
995
+ const getAnimated = owner => owner && owner[$node];
996
+ const setAnimated = (owner, node) => defineHidden(owner, $node, node);
997
+ const getPayload = owner => owner && owner[$node] && owner[$node].getPayload();
998
+ class Animated {
999
+ constructor() {
1000
+ this.payload = void 0;
1001
+ setAnimated(this, this);
1002
+ }
1003
+
1004
+ getPayload() {
1005
+ return this.payload || [];
1006
+ }
1007
+
1008
+ }
1009
+
1010
+ class AnimatedValue extends Animated {
1011
+ constructor(_value) {
1012
+ super();
1013
+ this.done = true;
1014
+ this.elapsedTime = void 0;
1015
+ this.lastPosition = void 0;
1016
+ this.lastVelocity = void 0;
1017
+ this.v0 = void 0;
1018
+ this.durationProgress = 0;
1019
+ this._value = _value;
1020
+
1021
+ if (is.num(this._value)) {
1022
+ this.lastPosition = this._value;
1023
+ }
1024
+ }
1025
+
1026
+ static create(value) {
1027
+ return new AnimatedValue(value);
1028
+ }
1029
+
1030
+ getPayload() {
1031
+ return [this];
1032
+ }
1033
+
1034
+ getValue() {
1035
+ return this._value;
1036
+ }
1037
+
1038
+ setValue(value, step) {
1039
+ if (is.num(value)) {
1040
+ this.lastPosition = value;
1041
+
1042
+ if (step) {
1043
+ value = Math.round(value / step) * step;
1044
+
1045
+ if (this.done) {
1046
+ this.lastPosition = value;
1047
+ }
1048
+ }
1049
+ }
1050
+
1051
+ if (this._value === value) {
1052
+ return false;
1053
+ }
1054
+
1055
+ this._value = value;
1056
+ return true;
1057
+ }
1058
+
1059
+ reset() {
1060
+ const {
1061
+ done
1062
+ } = this;
1063
+ this.done = false;
1064
+
1065
+ if (is.num(this._value)) {
1066
+ this.elapsedTime = 0;
1067
+ this.durationProgress = 0;
1068
+ this.lastPosition = this._value;
1069
+ if (done) this.lastVelocity = null;
1070
+ this.v0 = null;
1071
+ }
1072
+ }
1073
+
1074
+ }
1075
+
1076
+ class AnimatedString extends AnimatedValue {
1077
+ constructor(value) {
1078
+ super(0);
1079
+ this._string = null;
1080
+ this._toString = void 0;
1081
+ this._toString = createInterpolator({
1082
+ output: [value, value]
1083
+ });
1084
+ }
1085
+
1086
+ static create(value) {
1087
+ return new AnimatedString(value);
1088
+ }
1089
+
1090
+ getValue() {
1091
+ let value = this._string;
1092
+ return value == null ? this._string = this._toString(this._value) : value;
1093
+ }
1094
+
1095
+ setValue(value) {
1096
+ if (is.str(value)) {
1097
+ if (value == this._string) {
1098
+ return false;
1099
+ }
1100
+
1101
+ this._string = value;
1102
+ this._value = 1;
1103
+ } else if (super.setValue(value)) {
1104
+ this._string = null;
1105
+ } else {
1106
+ return false;
1107
+ }
1108
+
1109
+ return true;
1110
+ }
1111
+
1112
+ reset(goal) {
1113
+ if (goal) {
1114
+ this._toString = createInterpolator({
1115
+ output: [this.getValue(), goal]
1116
+ });
1117
+ }
1118
+
1119
+ this._value = 0;
1120
+ super.reset();
1121
+ }
1122
+
1123
+ }
1124
+
1125
+ const TreeContext = {
1126
+ dependencies: null
1127
+ };
1128
+
1129
+ class AnimatedObject extends Animated {
1130
+ constructor(source) {
1131
+ super();
1132
+ this.source = source;
1133
+ this.setValue(source);
1134
+ }
1135
+
1136
+ getValue(animated) {
1137
+ const values = {};
1138
+ eachProp(this.source, (source, key) => {
1139
+ if (isAnimated(source)) {
1140
+ values[key] = source.getValue(animated);
1141
+ } else if (hasFluidValue(source)) {
1142
+ values[key] = getFluidValue(source);
1143
+ } else if (!animated) {
1144
+ values[key] = source;
1145
+ }
1146
+ });
1147
+ return values;
1148
+ }
1149
+
1150
+ setValue(source) {
1151
+ this.source = source;
1152
+ this.payload = this._makePayload(source);
1153
+ }
1154
+
1155
+ reset() {
1156
+ if (this.payload) {
1157
+ each(this.payload, node => node.reset());
1158
+ }
1159
+ }
1160
+
1161
+ _makePayload(source) {
1162
+ if (source) {
1163
+ const payload = new Set();
1164
+ eachProp(source, this._addToPayload, payload);
1165
+ return Array.from(payload);
1166
+ }
1167
+ }
1168
+
1169
+ _addToPayload(source) {
1170
+ if (TreeContext.dependencies && hasFluidValue(source)) {
1171
+ TreeContext.dependencies.add(source);
1172
+ }
1173
+
1174
+ const payload = getPayload(source);
1175
+
1176
+ if (payload) {
1177
+ each(payload, node => this.add(node));
1178
+ }
1179
+ }
1180
+
1181
+ }
1182
+
1183
+ class AnimatedArray extends AnimatedObject {
1184
+ constructor(source) {
1185
+ super(source);
1186
+ }
1187
+
1188
+ static create(source) {
1189
+ return new AnimatedArray(source);
1190
+ }
1191
+
1192
+ getValue() {
1193
+ return this.source.map(node => node.getValue());
1194
+ }
1195
+
1196
+ setValue(source) {
1197
+ const payload = this.getPayload();
1198
+
1199
+ if (source.length == payload.length) {
1200
+ return payload.map((node, i) => node.setValue(source[i])).some(Boolean);
1201
+ }
1202
+
1203
+ super.setValue(source.map(makeAnimated));
1204
+ return true;
1205
+ }
1206
+
1207
+ }
1208
+
1209
+ function makeAnimated(value) {
1210
+ const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue;
1211
+ return nodeType.create(value);
1212
+ }
1213
+
1214
+ function getAnimatedType(value) {
1215
+ const parentNode = getAnimated(value);
1216
+ return parentNode ? parentNode.constructor : is.arr(value) ? AnimatedArray : isAnimatedString(value) ? AnimatedString : AnimatedValue;
1217
+ }
1218
+
1219
+ function _extends$1() {
1220
+ _extends$1 = Object.assign ? Object.assign.bind() : function (target) {
1221
+ for (var i = 1; i < arguments.length; i++) {
1222
+ var source = arguments[i];
1223
+
1224
+ for (var key in source) {
1225
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
1226
+ target[key] = source[key];
1227
+ }
1228
+ }
1229
+ }
1230
+
1231
+ return target;
1232
+ };
1233
+ return _extends$1.apply(this, arguments);
1234
+ }
1235
+
1236
+ const withAnimated = (Component, host) => {
1237
+ const hasInstance = !is.fun(Component) || Component.prototype && Component.prototype.isReactComponent;
1238
+ return React.forwardRef((givenProps, givenRef) => {
1239
+ const instanceRef = React.useRef(null);
1240
+ const ref = hasInstance && React.useCallback(value => {
1241
+ instanceRef.current = updateRef(givenRef, value);
1242
+ }, [givenRef]);
1243
+ const [props, deps] = getAnimatedState(givenProps, host);
1244
+ const forceUpdate = useForceUpdate();
1245
+
1246
+ const callback = () => {
1247
+ const instance = instanceRef.current;
1248
+
1249
+ if (hasInstance && !instance) {
1250
+ return;
1251
+ }
1252
+
1253
+ const didUpdate = instance ? host.applyAnimatedValues(instance, props.getValue(true)) : false;
1254
+
1255
+ if (didUpdate === false) {
1256
+ forceUpdate();
1257
+ }
1258
+ };
1259
+
1260
+ const observer = new PropsObserver(callback, deps);
1261
+ const observerRef = React.useRef();
1262
+ useIsomorphicLayoutEffect(() => {
1263
+ observerRef.current = observer;
1264
+ each(deps, dep => addFluidObserver(dep, observer));
1265
+ return () => {
1266
+ if (observerRef.current) {
1267
+ each(observerRef.current.deps, dep => removeFluidObserver(dep, observerRef.current));
1268
+ raf.cancel(observerRef.current.update);
1269
+ }
1270
+ };
1271
+ });
1272
+ React.useEffect(callback, []);
1273
+ useOnce(() => () => {
1274
+ const observer = observerRef.current;
1275
+ each(observer.deps, dep => removeFluidObserver(dep, observer));
1276
+ });
1277
+ const usedProps = host.getComponentProps(props.getValue());
1278
+ return React__namespace.createElement(Component, _extends$1({}, usedProps, {
1279
+ ref: ref
1280
+ }));
1281
+ });
1282
+ };
1283
+
1284
+ class PropsObserver {
1285
+ constructor(update, deps) {
1286
+ this.update = update;
1287
+ this.deps = deps;
1288
+ }
1289
+
1290
+ eventObserved(event) {
1291
+ if (event.type == 'change') {
1292
+ raf.write(this.update);
1293
+ }
1294
+ }
1295
+
1296
+ }
1297
+
1298
+ function getAnimatedState(props, host) {
1299
+ const dependencies = new Set();
1300
+ TreeContext.dependencies = dependencies;
1301
+ if (props.style) props = _extends$1({}, props, {
1302
+ style: host.createAnimatedStyle(props.style)
1303
+ });
1304
+ props = new AnimatedObject(props);
1305
+ TreeContext.dependencies = null;
1306
+ return [props, dependencies];
1307
+ }
1308
+
1309
+ function updateRef(ref, value) {
1310
+ if (ref) {
1311
+ if (is.fun(ref)) ref(value);else ref.current = value;
1312
+ }
1313
+
1314
+ return value;
1315
+ }
1316
+
1317
+ const cacheKey = Symbol.for('AnimatedComponent');
1318
+ const createHost = (components, {
1319
+ applyAnimatedValues: _applyAnimatedValues = () => false,
1320
+ createAnimatedStyle: _createAnimatedStyle = style => new AnimatedObject(style),
1321
+ getComponentProps: _getComponentProps = props => props
1322
+ } = {}) => {
1323
+ const hostConfig = {
1324
+ applyAnimatedValues: _applyAnimatedValues,
1325
+ createAnimatedStyle: _createAnimatedStyle,
1326
+ getComponentProps: _getComponentProps
1327
+ };
1328
+
1329
+ const animated = Component => {
1330
+ const displayName = getDisplayName(Component) || 'Anonymous';
1331
+
1332
+ if (is.str(Component)) {
1333
+ Component = animated[Component] || (animated[Component] = withAnimated(Component, hostConfig));
1334
+ } else {
1335
+ Component = Component[cacheKey] || (Component[cacheKey] = withAnimated(Component, hostConfig));
1336
+ }
1337
+
1338
+ Component.displayName = `Animated(${displayName})`;
1339
+ return Component;
1340
+ };
1341
+
1342
+ eachProp(components, (Component, key) => {
1343
+ if (is.arr(components)) {
1344
+ key = getDisplayName(Component);
1345
+ }
1346
+
1347
+ animated[key] = animated(Component);
1348
+ });
1349
+ return {
1350
+ animated
1351
+ };
1352
+ };
1353
+
1354
+ const getDisplayName = arg => is.str(arg) ? arg : arg && is.str(arg.displayName) ? arg.displayName : is.fun(arg) && arg.name || null;
1355
+
1356
+ function _extends() {
1357
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
1358
+ for (var i = 1; i < arguments.length; i++) {
1359
+ var source = arguments[i];
1360
+
1361
+ for (var key in source) {
1362
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
1363
+ target[key] = source[key];
1364
+ }
1365
+ }
1366
+ }
1367
+
1368
+ return target;
1369
+ };
1370
+ return _extends.apply(this, arguments);
1371
+ }
1372
+
1373
+ function callProp(value, ...args) {
1374
+ return is.fun(value) ? value(...args) : value;
1375
+ }
1376
+ const matchProp = (value, key) => value === true || !!(key && value && (is.fun(value) ? value(key) : toArray(value).includes(key)));
1377
+ const resolveProp = (prop, key) => is.obj(prop) ? key && prop[key] : prop;
1378
+ const getDefaultProp = (props, key) => props.default === true ? props[key] : props.default ? props.default[key] : undefined;
1379
+
1380
+ const noopTransform = value => value;
1381
+
1382
+ const getDefaultProps = (props, transform = noopTransform) => {
1383
+ let keys = DEFAULT_PROPS;
1384
+
1385
+ if (props.default && props.default !== true) {
1386
+ props = props.default;
1387
+ keys = Object.keys(props);
1388
+ }
1389
+
1390
+ const defaults = {};
1391
+
1392
+ for (const key of keys) {
1393
+ const value = transform(props[key], key);
1394
+
1395
+ if (!is.und(value)) {
1396
+ defaults[key] = value;
1397
+ }
1398
+ }
1399
+
1400
+ return defaults;
1401
+ };
1402
+ const DEFAULT_PROPS = ['config', 'onProps', 'onStart', 'onChange', 'onPause', 'onResume', 'onRest'];
1403
+ const RESERVED_PROPS = {
1404
+ config: 1,
1405
+ from: 1,
1406
+ to: 1,
1407
+ ref: 1,
1408
+ loop: 1,
1409
+ reset: 1,
1410
+ pause: 1,
1411
+ cancel: 1,
1412
+ reverse: 1,
1413
+ immediate: 1,
1414
+ default: 1,
1415
+ delay: 1,
1416
+ onProps: 1,
1417
+ onStart: 1,
1418
+ onChange: 1,
1419
+ onPause: 1,
1420
+ onResume: 1,
1421
+ onRest: 1,
1422
+ onResolve: 1,
1423
+ items: 1,
1424
+ trail: 1,
1425
+ sort: 1,
1426
+ expires: 1,
1427
+ initial: 1,
1428
+ enter: 1,
1429
+ update: 1,
1430
+ leave: 1,
1431
+ children: 1,
1432
+ onDestroyed: 1,
1433
+ keys: 1,
1434
+ callId: 1,
1435
+ parentId: 1
1436
+ };
1437
+
1438
+ function getForwardProps(props) {
1439
+ const forward = {};
1440
+ let count = 0;
1441
+ eachProp(props, (value, prop) => {
1442
+ if (!RESERVED_PROPS[prop]) {
1443
+ forward[prop] = value;
1444
+ count++;
1445
+ }
1446
+ });
1447
+
1448
+ if (count) {
1449
+ return forward;
1450
+ }
1451
+ }
1452
+
1453
+ function inferTo(props) {
1454
+ const to = getForwardProps(props);
1455
+
1456
+ if (to) {
1457
+ const out = {
1458
+ to
1459
+ };
1460
+ eachProp(props, (val, key) => key in to || (out[key] = val));
1461
+ return out;
1462
+ }
1463
+
1464
+ return _extends({}, props);
1465
+ }
1466
+ function computeGoal(value) {
1467
+ value = getFluidValue(value);
1468
+ return is.arr(value) ? value.map(computeGoal) : isAnimatedString(value) ? globals.createStringInterpolator({
1469
+ range: [0, 1],
1470
+ output: [value, value]
1471
+ })(1) : value;
1472
+ }
1473
+ function hasProps(props) {
1474
+ for (const _ in props) return true;
1475
+
1476
+ return false;
1477
+ }
1478
+ function isAsyncTo(to) {
1479
+ return is.fun(to) || is.arr(to) && is.obj(to[0]);
1480
+ }
1481
+ function detachRefs(ctrl, ref) {
1482
+ var _ctrl$ref;
1483
+
1484
+ (_ctrl$ref = ctrl.ref) == null ? void 0 : _ctrl$ref.delete(ctrl);
1485
+ ref == null ? void 0 : ref.delete(ctrl);
1486
+ }
1487
+ function replaceRef(ctrl, ref) {
1488
+ if (ref && ctrl.ref !== ref) {
1489
+ var _ctrl$ref2;
1490
+
1491
+ (_ctrl$ref2 = ctrl.ref) == null ? void 0 : _ctrl$ref2.delete(ctrl);
1492
+ ref.add(ctrl);
1493
+ ctrl.ref = ref;
1494
+ }
1495
+ }
1496
+
1497
+ const config = {
1498
+ default: {
1499
+ tension: 170,
1500
+ friction: 26
1501
+ },
1502
+ gentle: {
1503
+ tension: 120,
1504
+ friction: 14
1505
+ },
1506
+ wobbly: {
1507
+ tension: 180,
1508
+ friction: 12
1509
+ },
1510
+ stiff: {
1511
+ tension: 210,
1512
+ friction: 20
1513
+ },
1514
+ slow: {
1515
+ tension: 280,
1516
+ friction: 60
1517
+ },
1518
+ molasses: {
1519
+ tension: 280,
1520
+ friction: 120
1521
+ }
1522
+ };
1523
+ const c1 = 1.70158;
1524
+ const c2 = c1 * 1.525;
1525
+ const c3 = c1 + 1;
1526
+ const c4 = 2 * Math.PI / 3;
1527
+ const c5 = 2 * Math.PI / 4.5;
1528
+
1529
+ const bounceOut = x => {
1530
+ const n1 = 7.5625;
1531
+ const d1 = 2.75;
1532
+
1533
+ if (x < 1 / d1) {
1534
+ return n1 * x * x;
1535
+ } else if (x < 2 / d1) {
1536
+ return n1 * (x -= 1.5 / d1) * x + 0.75;
1537
+ } else if (x < 2.5 / d1) {
1538
+ return n1 * (x -= 2.25 / d1) * x + 0.9375;
1539
+ } else {
1540
+ return n1 * (x -= 2.625 / d1) * x + 0.984375;
1541
+ }
1542
+ };
1543
+
1544
+ const easings = {
1545
+ linear: x => x,
1546
+ easeInQuad: x => x * x,
1547
+ easeOutQuad: x => 1 - (1 - x) * (1 - x),
1548
+ easeInOutQuad: x => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2,
1549
+ easeInCubic: x => x * x * x,
1550
+ easeOutCubic: x => 1 - Math.pow(1 - x, 3),
1551
+ easeInOutCubic: x => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2,
1552
+ easeInQuart: x => x * x * x * x,
1553
+ easeOutQuart: x => 1 - Math.pow(1 - x, 4),
1554
+ easeInOutQuart: x => x < 0.5 ? 8 * x * x * x * x : 1 - Math.pow(-2 * x + 2, 4) / 2,
1555
+ easeInQuint: x => x * x * x * x * x,
1556
+ easeOutQuint: x => 1 - Math.pow(1 - x, 5),
1557
+ easeInOutQuint: x => x < 0.5 ? 16 * x * x * x * x * x : 1 - Math.pow(-2 * x + 2, 5) / 2,
1558
+ easeInSine: x => 1 - Math.cos(x * Math.PI / 2),
1559
+ easeOutSine: x => Math.sin(x * Math.PI / 2),
1560
+ easeInOutSine: x => -(Math.cos(Math.PI * x) - 1) / 2,
1561
+ easeInExpo: x => x === 0 ? 0 : Math.pow(2, 10 * x - 10),
1562
+ easeOutExpo: x => x === 1 ? 1 : 1 - Math.pow(2, -10 * x),
1563
+ easeInOutExpo: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? Math.pow(2, 20 * x - 10) / 2 : (2 - Math.pow(2, -20 * x + 10)) / 2,
1564
+ easeInCirc: x => 1 - Math.sqrt(1 - Math.pow(x, 2)),
1565
+ easeOutCirc: x => Math.sqrt(1 - Math.pow(x - 1, 2)),
1566
+ easeInOutCirc: x => x < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2,
1567
+ easeInBack: x => c3 * x * x * x - c1 * x * x,
1568
+ easeOutBack: x => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2),
1569
+ easeInOutBack: x => x < 0.5 ? Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2) / 2 : (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2,
1570
+ easeInElastic: x => x === 0 ? 0 : x === 1 ? 1 : -Math.pow(2, 10 * x - 10) * Math.sin((x * 10 - 10.75) * c4),
1571
+ easeOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1,
1572
+ easeInOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? -(Math.pow(2, 20 * x - 10) * Math.sin((20 * x - 11.125) * c5)) / 2 : Math.pow(2, -20 * x + 10) * Math.sin((20 * x - 11.125) * c5) / 2 + 1,
1573
+ easeInBounce: x => 1 - bounceOut(1 - x),
1574
+ easeOutBounce: bounceOut,
1575
+ easeInOutBounce: x => x < 0.5 ? (1 - bounceOut(1 - 2 * x)) / 2 : (1 + bounceOut(2 * x - 1)) / 2
1576
+ };
1577
+
1578
+ const defaults = _extends({}, config.default, {
1579
+ mass: 1,
1580
+ damping: 1,
1581
+ easing: easings.linear,
1582
+ clamp: false
1583
+ });
1584
+
1585
+ class AnimationConfig {
1586
+ constructor() {
1587
+ this.tension = void 0;
1588
+ this.friction = void 0;
1589
+ this.frequency = void 0;
1590
+ this.damping = void 0;
1591
+ this.mass = void 0;
1592
+ this.velocity = 0;
1593
+ this.restVelocity = void 0;
1594
+ this.precision = void 0;
1595
+ this.progress = void 0;
1596
+ this.duration = void 0;
1597
+ this.easing = void 0;
1598
+ this.clamp = void 0;
1599
+ this.bounce = void 0;
1600
+ this.decay = void 0;
1601
+ this.round = void 0;
1602
+ Object.assign(this, defaults);
1603
+ }
1604
+
1605
+ }
1606
+ function mergeConfig(config, newConfig, defaultConfig) {
1607
+ if (defaultConfig) {
1608
+ defaultConfig = _extends({}, defaultConfig);
1609
+ sanitizeConfig(defaultConfig, newConfig);
1610
+ newConfig = _extends({}, defaultConfig, newConfig);
1611
+ }
1612
+
1613
+ sanitizeConfig(config, newConfig);
1614
+ Object.assign(config, newConfig);
1615
+
1616
+ for (const key in defaults) {
1617
+ if (config[key] == null) {
1618
+ config[key] = defaults[key];
1619
+ }
1620
+ }
1621
+
1622
+ let {
1623
+ mass,
1624
+ frequency,
1625
+ damping
1626
+ } = config;
1627
+
1628
+ if (!is.und(frequency)) {
1629
+ if (frequency < 0.01) frequency = 0.01;
1630
+ if (damping < 0) damping = 0;
1631
+ config.tension = Math.pow(2 * Math.PI / frequency, 2) * mass;
1632
+ config.friction = 4 * Math.PI * damping * mass / frequency;
1633
+ }
1634
+
1635
+ return config;
1636
+ }
1637
+
1638
+ function sanitizeConfig(config, props) {
1639
+ if (!is.und(props.decay)) {
1640
+ config.duration = undefined;
1641
+ } else {
1642
+ const isTensionConfig = !is.und(props.tension) || !is.und(props.friction);
1643
+
1644
+ if (isTensionConfig || !is.und(props.frequency) || !is.und(props.damping) || !is.und(props.mass)) {
1645
+ config.duration = undefined;
1646
+ config.decay = undefined;
1647
+ }
1648
+
1649
+ if (isTensionConfig) {
1650
+ config.frequency = undefined;
1651
+ }
1652
+ }
1653
+ }
1654
+
1655
+ const emptyArray = [];
1656
+ class Animation {
1657
+ constructor() {
1658
+ this.changed = false;
1659
+ this.values = emptyArray;
1660
+ this.toValues = null;
1661
+ this.fromValues = emptyArray;
1662
+ this.to = void 0;
1663
+ this.from = void 0;
1664
+ this.config = new AnimationConfig();
1665
+ this.immediate = false;
1666
+ }
1667
+
1668
+ }
1669
+
1670
+ function scheduleProps(callId, {
1671
+ key,
1672
+ props,
1673
+ defaultProps,
1674
+ state,
1675
+ actions
1676
+ }) {
1677
+ return new Promise((resolve, reject) => {
1678
+ var _props$cancel;
1679
+
1680
+ let delay;
1681
+ let timeout;
1682
+ let cancel = matchProp((_props$cancel = props.cancel) != null ? _props$cancel : defaultProps == null ? void 0 : defaultProps.cancel, key);
1683
+
1684
+ if (cancel) {
1685
+ onStart();
1686
+ } else {
1687
+ if (!is.und(props.pause)) {
1688
+ state.paused = matchProp(props.pause, key);
1689
+ }
1690
+
1691
+ let pause = defaultProps == null ? void 0 : defaultProps.pause;
1692
+
1693
+ if (pause !== true) {
1694
+ pause = state.paused || matchProp(pause, key);
1695
+ }
1696
+
1697
+ delay = callProp(props.delay || 0, key);
1698
+
1699
+ if (pause) {
1700
+ state.resumeQueue.add(onResume);
1701
+ actions.pause();
1702
+ } else {
1703
+ actions.resume();
1704
+ onResume();
1705
+ }
1706
+ }
1707
+
1708
+ function onPause() {
1709
+ state.resumeQueue.add(onResume);
1710
+ state.timeouts.delete(timeout);
1711
+ timeout.cancel();
1712
+ delay = timeout.time - raf.now();
1713
+ }
1714
+
1715
+ function onResume() {
1716
+ if (delay > 0 && !globals.skipAnimation) {
1717
+ state.delayed = true;
1718
+ timeout = raf.setTimeout(onStart, delay);
1719
+ state.pauseQueue.add(onPause);
1720
+ state.timeouts.add(timeout);
1721
+ } else {
1722
+ onStart();
1723
+ }
1724
+ }
1725
+
1726
+ function onStart() {
1727
+ if (state.delayed) {
1728
+ state.delayed = false;
1729
+ }
1730
+
1731
+ state.pauseQueue.delete(onPause);
1732
+ state.timeouts.delete(timeout);
1733
+
1734
+ if (callId <= (state.cancelId || 0)) {
1735
+ cancel = true;
1736
+ }
1737
+
1738
+ try {
1739
+ actions.start(_extends({}, props, {
1740
+ callId,
1741
+ cancel
1742
+ }), resolve);
1743
+ } catch (err) {
1744
+ reject(err);
1745
+ }
1746
+ }
1747
+ });
1748
+ }
1749
+
1750
+ const getCombinedResult = (target, results) => results.length == 1 ? results[0] : results.some(result => result.cancelled) ? getCancelledResult(target.get()) : results.every(result => result.noop) ? getNoopResult(target.get()) : getFinishedResult(target.get(), results.every(result => result.finished));
1751
+ const getNoopResult = value => ({
1752
+ value,
1753
+ noop: true,
1754
+ finished: true,
1755
+ cancelled: false
1756
+ });
1757
+ const getFinishedResult = (value, finished, cancelled = false) => ({
1758
+ value,
1759
+ finished,
1760
+ cancelled
1761
+ });
1762
+ const getCancelledResult = value => ({
1763
+ value,
1764
+ cancelled: true,
1765
+ finished: false
1766
+ });
1767
+
1768
+ function runAsync(to, props, state, target) {
1769
+ const {
1770
+ callId,
1771
+ parentId,
1772
+ onRest
1773
+ } = props;
1774
+ const {
1775
+ asyncTo: prevTo,
1776
+ promise: prevPromise
1777
+ } = state;
1778
+
1779
+ if (!parentId && to === prevTo && !props.reset) {
1780
+ return prevPromise;
1781
+ }
1782
+
1783
+ return state.promise = (async () => {
1784
+ state.asyncId = callId;
1785
+ state.asyncTo = to;
1786
+ const defaultProps = getDefaultProps(props, (value, key) => key === 'onRest' ? undefined : value);
1787
+ let preventBail;
1788
+ let bail;
1789
+ const bailPromise = new Promise((resolve, reject) => (preventBail = resolve, bail = reject));
1790
+
1791
+ const bailIfEnded = bailSignal => {
1792
+ const bailResult = callId <= (state.cancelId || 0) && getCancelledResult(target) || callId !== state.asyncId && getFinishedResult(target, false);
1793
+
1794
+ if (bailResult) {
1795
+ bailSignal.result = bailResult;
1796
+ bail(bailSignal);
1797
+ throw bailSignal;
1798
+ }
1799
+ };
1800
+
1801
+ const animate = (arg1, arg2) => {
1802
+ const bailSignal = new BailSignal();
1803
+ const skipAnimationSignal = new SkipAniamtionSignal();
1804
+ return (async () => {
1805
+ if (globals.skipAnimation) {
1806
+ stopAsync(state);
1807
+ skipAnimationSignal.result = getFinishedResult(target, false);
1808
+ bail(skipAnimationSignal);
1809
+ throw skipAnimationSignal;
1810
+ }
1811
+
1812
+ bailIfEnded(bailSignal);
1813
+ const props = is.obj(arg1) ? _extends({}, arg1) : _extends({}, arg2, {
1814
+ to: arg1
1815
+ });
1816
+ props.parentId = callId;
1817
+ eachProp(defaultProps, (value, key) => {
1818
+ if (is.und(props[key])) {
1819
+ props[key] = value;
1820
+ }
1821
+ });
1822
+ const result = await target.start(props);
1823
+ bailIfEnded(bailSignal);
1824
+
1825
+ if (state.paused) {
1826
+ await new Promise(resume => {
1827
+ state.resumeQueue.add(resume);
1828
+ });
1829
+ }
1830
+
1831
+ return result;
1832
+ })();
1833
+ };
1834
+
1835
+ let result;
1836
+
1837
+ if (globals.skipAnimation) {
1838
+ stopAsync(state);
1839
+ return getFinishedResult(target, false);
1840
+ }
1841
+
1842
+ try {
1843
+ let animating;
1844
+
1845
+ if (is.arr(to)) {
1846
+ animating = (async queue => {
1847
+ for (const props of queue) {
1848
+ await animate(props);
1849
+ }
1850
+ })(to);
1851
+ } else {
1852
+ animating = Promise.resolve(to(animate, target.stop.bind(target)));
1853
+ }
1854
+
1855
+ await Promise.all([animating.then(preventBail), bailPromise]);
1856
+ result = getFinishedResult(target.get(), true, false);
1857
+ } catch (err) {
1858
+ if (err instanceof BailSignal) {
1859
+ result = err.result;
1860
+ } else if (err instanceof SkipAniamtionSignal) {
1861
+ result = err.result;
1862
+ } else {
1863
+ throw err;
1864
+ }
1865
+ } finally {
1866
+ if (callId == state.asyncId) {
1867
+ state.asyncId = parentId;
1868
+ state.asyncTo = parentId ? prevTo : undefined;
1869
+ state.promise = parentId ? prevPromise : undefined;
1870
+ }
1871
+ }
1872
+
1873
+ if (is.fun(onRest)) {
1874
+ raf.batchedUpdates(() => {
1875
+ onRest(result, target, target.item);
1876
+ });
1877
+ }
1878
+
1879
+ return result;
1880
+ })();
1881
+ }
1882
+ function stopAsync(state, cancelId) {
1883
+ flush(state.timeouts, t => t.cancel());
1884
+ state.pauseQueue.clear();
1885
+ state.resumeQueue.clear();
1886
+ state.asyncId = state.asyncTo = state.promise = undefined;
1887
+ if (cancelId) state.cancelId = cancelId;
1888
+ }
1889
+ class BailSignal extends Error {
1890
+ constructor() {
1891
+ super('An async animation has been interrupted. You see this error because you ' + 'forgot to use `await` or `.catch(...)` on its returned promise.');
1892
+ this.result = void 0;
1893
+ }
1894
+
1895
+ }
1896
+ class SkipAniamtionSignal extends Error {
1897
+ constructor() {
1898
+ super('SkipAnimationSignal');
1899
+ this.result = void 0;
1900
+ }
1901
+
1902
+ }
1903
+
1904
+ const isFrameValue = value => value instanceof FrameValue;
1905
+ let nextId$1 = 1;
1906
+ class FrameValue extends FluidValue {
1907
+ constructor(...args) {
1908
+ super(...args);
1909
+ this.id = nextId$1++;
1910
+ this.key = void 0;
1911
+ this._priority = 0;
1912
+ }
1913
+
1914
+ get priority() {
1915
+ return this._priority;
1916
+ }
1917
+
1918
+ set priority(priority) {
1919
+ if (this._priority != priority) {
1920
+ this._priority = priority;
1921
+
1922
+ this._onPriorityChange(priority);
1923
+ }
1924
+ }
1925
+
1926
+ get() {
1927
+ const node = getAnimated(this);
1928
+ return node && node.getValue();
1929
+ }
1930
+
1931
+ to(...args) {
1932
+ return globals.to(this, args);
1933
+ }
1934
+
1935
+ interpolate(...args) {
1936
+ deprecateInterpolate();
1937
+ return globals.to(this, args);
1938
+ }
1939
+
1940
+ toJSON() {
1941
+ return this.get();
1942
+ }
1943
+
1944
+ observerAdded(count) {
1945
+ if (count == 1) this._attach();
1946
+ }
1947
+
1948
+ observerRemoved(count) {
1949
+ if (count == 0) this._detach();
1950
+ }
1951
+
1952
+ _attach() {}
1953
+
1954
+ _detach() {}
1955
+
1956
+ _onChange(value, idle = false) {
1957
+ callFluidObservers(this, {
1958
+ type: 'change',
1959
+ parent: this,
1960
+ value,
1961
+ idle
1962
+ });
1963
+ }
1964
+
1965
+ _onPriorityChange(priority) {
1966
+ if (!this.idle) {
1967
+ frameLoop.sort(this);
1968
+ }
1969
+
1970
+ callFluidObservers(this, {
1971
+ type: 'priority',
1972
+ parent: this,
1973
+ priority
1974
+ });
1975
+ }
1976
+
1977
+ }
1978
+
1979
+ const $P = Symbol.for('SpringPhase');
1980
+ const HAS_ANIMATED = 1;
1981
+ const IS_ANIMATING = 2;
1982
+ const IS_PAUSED = 4;
1983
+ const hasAnimated = target => (target[$P] & HAS_ANIMATED) > 0;
1984
+ const isAnimating = target => (target[$P] & IS_ANIMATING) > 0;
1985
+ const isPaused = target => (target[$P] & IS_PAUSED) > 0;
1986
+ const setActiveBit = (target, active) => active ? target[$P] |= IS_ANIMATING | HAS_ANIMATED : target[$P] &= ~IS_ANIMATING;
1987
+ const setPausedBit = (target, paused) => paused ? target[$P] |= IS_PAUSED : target[$P] &= ~IS_PAUSED;
1988
+
1989
+ class SpringValue extends FrameValue {
1990
+ constructor(arg1, arg2) {
1991
+ super();
1992
+ this.key = void 0;
1993
+ this.animation = new Animation();
1994
+ this.queue = void 0;
1995
+ this.defaultProps = {};
1996
+ this._state = {
1997
+ paused: false,
1998
+ delayed: false,
1999
+ pauseQueue: new Set(),
2000
+ resumeQueue: new Set(),
2001
+ timeouts: new Set()
2002
+ };
2003
+ this._pendingCalls = new Set();
2004
+ this._lastCallId = 0;
2005
+ this._lastToId = 0;
2006
+ this._memoizedDuration = 0;
2007
+
2008
+ if (!is.und(arg1) || !is.und(arg2)) {
2009
+ const props = is.obj(arg1) ? _extends({}, arg1) : _extends({}, arg2, {
2010
+ from: arg1
2011
+ });
2012
+
2013
+ if (is.und(props.default)) {
2014
+ props.default = true;
2015
+ }
2016
+
2017
+ this.start(props);
2018
+ }
2019
+ }
2020
+
2021
+ get idle() {
2022
+ return !(isAnimating(this) || this._state.asyncTo) || isPaused(this);
2023
+ }
2024
+
2025
+ get goal() {
2026
+ return getFluidValue(this.animation.to);
2027
+ }
2028
+
2029
+ get velocity() {
2030
+ const node = getAnimated(this);
2031
+ return node instanceof AnimatedValue ? node.lastVelocity || 0 : node.getPayload().map(node => node.lastVelocity || 0);
2032
+ }
2033
+
2034
+ get hasAnimated() {
2035
+ return hasAnimated(this);
2036
+ }
2037
+
2038
+ get isAnimating() {
2039
+ return isAnimating(this);
2040
+ }
2041
+
2042
+ get isPaused() {
2043
+ return isPaused(this);
2044
+ }
2045
+
2046
+ get isDelayed() {
2047
+ return this._state.delayed;
2048
+ }
2049
+
2050
+ advance(dt) {
2051
+ let idle = true;
2052
+ let changed = false;
2053
+ const anim = this.animation;
2054
+ let {
2055
+ config,
2056
+ toValues
2057
+ } = anim;
2058
+ const payload = getPayload(anim.to);
2059
+
2060
+ if (!payload && hasFluidValue(anim.to)) {
2061
+ toValues = toArray(getFluidValue(anim.to));
2062
+ }
2063
+
2064
+ anim.values.forEach((node, i) => {
2065
+ if (node.done) return;
2066
+ const to = node.constructor == AnimatedString ? 1 : payload ? payload[i].lastPosition : toValues[i];
2067
+ let finished = anim.immediate;
2068
+ let position = to;
2069
+
2070
+ if (!finished) {
2071
+ position = node.lastPosition;
2072
+
2073
+ if (config.tension <= 0) {
2074
+ node.done = true;
2075
+ return;
2076
+ }
2077
+
2078
+ let elapsed = node.elapsedTime += dt;
2079
+ const from = anim.fromValues[i];
2080
+ const v0 = node.v0 != null ? node.v0 : node.v0 = is.arr(config.velocity) ? config.velocity[i] : config.velocity;
2081
+ let velocity;
2082
+ const precision = config.precision || (from == to ? 0.005 : Math.min(1, Math.abs(to - from) * 0.001));
2083
+
2084
+ if (!is.und(config.duration)) {
2085
+ let p = 1;
2086
+
2087
+ if (config.duration > 0) {
2088
+ if (this._memoizedDuration !== config.duration) {
2089
+ this._memoizedDuration = config.duration;
2090
+
2091
+ if (node.durationProgress > 0) {
2092
+ node.elapsedTime = config.duration * node.durationProgress;
2093
+ elapsed = node.elapsedTime += dt;
2094
+ }
2095
+ }
2096
+
2097
+ p = (config.progress || 0) + elapsed / this._memoizedDuration;
2098
+ p = p > 1 ? 1 : p < 0 ? 0 : p;
2099
+ node.durationProgress = p;
2100
+ }
2101
+
2102
+ position = from + config.easing(p) * (to - from);
2103
+ velocity = (position - node.lastPosition) / dt;
2104
+ finished = p == 1;
2105
+ } else if (config.decay) {
2106
+ const decay = config.decay === true ? 0.998 : config.decay;
2107
+ const e = Math.exp(-(1 - decay) * elapsed);
2108
+ position = from + v0 / (1 - decay) * (1 - e);
2109
+ finished = Math.abs(node.lastPosition - position) <= precision;
2110
+ velocity = v0 * e;
2111
+ } else {
2112
+ velocity = node.lastVelocity == null ? v0 : node.lastVelocity;
2113
+ const restVelocity = config.restVelocity || precision / 10;
2114
+ const bounceFactor = config.clamp ? 0 : config.bounce;
2115
+ const canBounce = !is.und(bounceFactor);
2116
+ const isGrowing = from == to ? node.v0 > 0 : from < to;
2117
+ let isMoving;
2118
+ let isBouncing = false;
2119
+ const step = 1;
2120
+ const numSteps = Math.ceil(dt / step);
2121
+
2122
+ for (let n = 0; n < numSteps; ++n) {
2123
+ isMoving = Math.abs(velocity) > restVelocity;
2124
+
2125
+ if (!isMoving) {
2126
+ finished = Math.abs(to - position) <= precision;
2127
+
2128
+ if (finished) {
2129
+ break;
2130
+ }
2131
+ }
2132
+
2133
+ if (canBounce) {
2134
+ isBouncing = position == to || position > to == isGrowing;
2135
+
2136
+ if (isBouncing) {
2137
+ velocity = -velocity * bounceFactor;
2138
+ position = to;
2139
+ }
2140
+ }
2141
+
2142
+ const springForce = -config.tension * 0.000001 * (position - to);
2143
+ const dampingForce = -config.friction * 0.001 * velocity;
2144
+ const acceleration = (springForce + dampingForce) / config.mass;
2145
+ velocity = velocity + acceleration * step;
2146
+ position = position + velocity * step;
2147
+ }
2148
+ }
2149
+
2150
+ node.lastVelocity = velocity;
2151
+
2152
+ if (Number.isNaN(position)) {
2153
+ console.warn(`Got NaN while animating:`, this);
2154
+ finished = true;
2155
+ }
2156
+ }
2157
+
2158
+ if (payload && !payload[i].done) {
2159
+ finished = false;
2160
+ }
2161
+
2162
+ if (finished) {
2163
+ node.done = true;
2164
+ } else {
2165
+ idle = false;
2166
+ }
2167
+
2168
+ if (node.setValue(position, config.round)) {
2169
+ changed = true;
2170
+ }
2171
+ });
2172
+ const node = getAnimated(this);
2173
+ const currVal = node.getValue();
2174
+
2175
+ if (idle) {
2176
+ const finalVal = getFluidValue(anim.to);
2177
+
2178
+ if ((currVal !== finalVal || changed) && !config.decay) {
2179
+ node.setValue(finalVal);
2180
+
2181
+ this._onChange(finalVal);
2182
+ } else if (changed && config.decay) {
2183
+ this._onChange(currVal);
2184
+ }
2185
+
2186
+ this._stop();
2187
+ } else if (changed) {
2188
+ this._onChange(currVal);
2189
+ }
2190
+ }
2191
+
2192
+ set(value) {
2193
+ raf.batchedUpdates(() => {
2194
+ this._stop();
2195
+
2196
+ this._focus(value);
2197
+
2198
+ this._set(value);
2199
+ });
2200
+ return this;
2201
+ }
2202
+
2203
+ pause() {
2204
+ this._update({
2205
+ pause: true
2206
+ });
2207
+ }
2208
+
2209
+ resume() {
2210
+ this._update({
2211
+ pause: false
2212
+ });
2213
+ }
2214
+
2215
+ finish() {
2216
+ if (isAnimating(this)) {
2217
+ const {
2218
+ to,
2219
+ config
2220
+ } = this.animation;
2221
+ raf.batchedUpdates(() => {
2222
+ this._onStart();
2223
+
2224
+ if (!config.decay) {
2225
+ this._set(to, false);
2226
+ }
2227
+
2228
+ this._stop();
2229
+ });
2230
+ }
2231
+
2232
+ return this;
2233
+ }
2234
+
2235
+ update(props) {
2236
+ const queue = this.queue || (this.queue = []);
2237
+ queue.push(props);
2238
+ return this;
2239
+ }
2240
+
2241
+ start(to, arg2) {
2242
+ let queue;
2243
+
2244
+ if (!is.und(to)) {
2245
+ queue = [is.obj(to) ? to : _extends({}, arg2, {
2246
+ to
2247
+ })];
2248
+ } else {
2249
+ queue = this.queue || [];
2250
+ this.queue = [];
2251
+ }
2252
+
2253
+ return Promise.all(queue.map(props => {
2254
+ const up = this._update(props);
2255
+
2256
+ return up;
2257
+ })).then(results => getCombinedResult(this, results));
2258
+ }
2259
+
2260
+ stop(cancel) {
2261
+ const {
2262
+ to
2263
+ } = this.animation;
2264
+
2265
+ this._focus(this.get());
2266
+
2267
+ stopAsync(this._state, cancel && this._lastCallId);
2268
+ raf.batchedUpdates(() => this._stop(to, cancel));
2269
+ return this;
2270
+ }
2271
+
2272
+ reset() {
2273
+ this._update({
2274
+ reset: true
2275
+ });
2276
+ }
2277
+
2278
+ eventObserved(event) {
2279
+ if (event.type == 'change') {
2280
+ this._start();
2281
+ } else if (event.type == 'priority') {
2282
+ this.priority = event.priority + 1;
2283
+ }
2284
+ }
2285
+
2286
+ _prepareNode(props) {
2287
+ const key = this.key || '';
2288
+ let {
2289
+ to,
2290
+ from
2291
+ } = props;
2292
+ to = is.obj(to) ? to[key] : to;
2293
+
2294
+ if (to == null || isAsyncTo(to)) {
2295
+ to = undefined;
2296
+ }
2297
+
2298
+ from = is.obj(from) ? from[key] : from;
2299
+
2300
+ if (from == null) {
2301
+ from = undefined;
2302
+ }
2303
+
2304
+ const range = {
2305
+ to,
2306
+ from
2307
+ };
2308
+
2309
+ if (!hasAnimated(this)) {
2310
+ if (props.reverse) [to, from] = [from, to];
2311
+ from = getFluidValue(from);
2312
+
2313
+ if (!is.und(from)) {
2314
+ this._set(from);
2315
+ } else if (!getAnimated(this)) {
2316
+ this._set(to);
2317
+ }
2318
+ }
2319
+
2320
+ return range;
2321
+ }
2322
+
2323
+ _update(_ref, isLoop) {
2324
+ let props = _extends({}, _ref);
2325
+
2326
+ const {
2327
+ key,
2328
+ defaultProps
2329
+ } = this;
2330
+ if (props.default) Object.assign(defaultProps, getDefaultProps(props, (value, prop) => /^on/.test(prop) ? resolveProp(value, key) : value));
2331
+ mergeActiveFn(this, props, 'onProps');
2332
+ sendEvent(this, 'onProps', props, this);
2333
+
2334
+ const range = this._prepareNode(props);
2335
+
2336
+ if (Object.isFrozen(this)) {
2337
+ throw Error('Cannot animate a `SpringValue` object that is frozen. ' + 'Did you forget to pass your component to `animated(...)` before animating its props?');
2338
+ }
2339
+
2340
+ const state = this._state;
2341
+ return scheduleProps(++this._lastCallId, {
2342
+ key,
2343
+ props,
2344
+ defaultProps,
2345
+ state,
2346
+ actions: {
2347
+ pause: () => {
2348
+ if (!isPaused(this)) {
2349
+ setPausedBit(this, true);
2350
+ flushCalls(state.pauseQueue);
2351
+ sendEvent(this, 'onPause', getFinishedResult(this, checkFinished(this, this.animation.to)), this);
2352
+ }
2353
+ },
2354
+ resume: () => {
2355
+ if (isPaused(this)) {
2356
+ setPausedBit(this, false);
2357
+
2358
+ if (isAnimating(this)) {
2359
+ this._resume();
2360
+ }
2361
+
2362
+ flushCalls(state.resumeQueue);
2363
+ sendEvent(this, 'onResume', getFinishedResult(this, checkFinished(this, this.animation.to)), this);
2364
+ }
2365
+ },
2366
+ start: this._merge.bind(this, range)
2367
+ }
2368
+ }).then(result => {
2369
+ if (props.loop && result.finished && !(isLoop && result.noop)) {
2370
+ const nextProps = createLoopUpdate(props);
2371
+
2372
+ if (nextProps) {
2373
+ return this._update(nextProps, true);
2374
+ }
2375
+ }
2376
+
2377
+ return result;
2378
+ });
2379
+ }
2380
+
2381
+ _merge(range, props, resolve) {
2382
+ if (props.cancel) {
2383
+ this.stop(true);
2384
+ return resolve(getCancelledResult(this));
2385
+ }
2386
+
2387
+ const hasToProp = !is.und(range.to);
2388
+ const hasFromProp = !is.und(range.from);
2389
+
2390
+ if (hasToProp || hasFromProp) {
2391
+ if (props.callId > this._lastToId) {
2392
+ this._lastToId = props.callId;
2393
+ } else {
2394
+ return resolve(getCancelledResult(this));
2395
+ }
2396
+ }
2397
+
2398
+ const {
2399
+ key,
2400
+ defaultProps,
2401
+ animation: anim
2402
+ } = this;
2403
+ const {
2404
+ to: prevTo,
2405
+ from: prevFrom
2406
+ } = anim;
2407
+ let {
2408
+ to = prevTo,
2409
+ from = prevFrom
2410
+ } = range;
2411
+
2412
+ if (hasFromProp && !hasToProp && (!props.default || is.und(to))) {
2413
+ to = from;
2414
+ }
2415
+
2416
+ if (props.reverse) [to, from] = [from, to];
2417
+ const hasFromChanged = !isEqual(from, prevFrom);
2418
+
2419
+ if (hasFromChanged) {
2420
+ anim.from = from;
2421
+ }
2422
+
2423
+ from = getFluidValue(from);
2424
+ const hasToChanged = !isEqual(to, prevTo);
2425
+
2426
+ if (hasToChanged) {
2427
+ this._focus(to);
2428
+ }
2429
+
2430
+ const hasAsyncTo = isAsyncTo(props.to);
2431
+ const {
2432
+ config
2433
+ } = anim;
2434
+ const {
2435
+ decay,
2436
+ velocity
2437
+ } = config;
2438
+
2439
+ if (hasToProp || hasFromProp) {
2440
+ config.velocity = 0;
2441
+ }
2442
+
2443
+ if (props.config && !hasAsyncTo) {
2444
+ mergeConfig(config, callProp(props.config, key), props.config !== defaultProps.config ? callProp(defaultProps.config, key) : void 0);
2445
+ }
2446
+
2447
+ let node = getAnimated(this);
2448
+
2449
+ if (!node || is.und(to)) {
2450
+ return resolve(getFinishedResult(this, true));
2451
+ }
2452
+
2453
+ const reset = is.und(props.reset) ? hasFromProp && !props.default : !is.und(from) && matchProp(props.reset, key);
2454
+ const value = reset ? from : this.get();
2455
+ const goal = computeGoal(to);
2456
+ const isAnimatable = is.num(goal) || is.arr(goal) || isAnimatedString(goal);
2457
+ const immediate = !hasAsyncTo && (!isAnimatable || matchProp(defaultProps.immediate || props.immediate, key));
2458
+
2459
+ if (hasToChanged) {
2460
+ const nodeType = getAnimatedType(to);
2461
+
2462
+ if (nodeType !== node.constructor) {
2463
+ if (immediate) {
2464
+ node = this._set(goal);
2465
+ } else throw Error(`Cannot animate between ${node.constructor.name} and ${nodeType.name}, as the "to" prop suggests`);
2466
+ }
2467
+ }
2468
+
2469
+ const goalType = node.constructor;
2470
+ let started = hasFluidValue(to);
2471
+ let finished = false;
2472
+
2473
+ if (!started) {
2474
+ const hasValueChanged = reset || !hasAnimated(this) && hasFromChanged;
2475
+
2476
+ if (hasToChanged || hasValueChanged) {
2477
+ finished = isEqual(computeGoal(value), goal);
2478
+ started = !finished;
2479
+ }
2480
+
2481
+ if (!isEqual(anim.immediate, immediate) && !immediate || !isEqual(config.decay, decay) || !isEqual(config.velocity, velocity)) {
2482
+ started = true;
2483
+ }
2484
+ }
2485
+
2486
+ if (finished && isAnimating(this)) {
2487
+ if (anim.changed && !reset) {
2488
+ started = true;
2489
+ } else if (!started) {
2490
+ this._stop(prevTo);
2491
+ }
2492
+ }
2493
+
2494
+ if (!hasAsyncTo) {
2495
+ if (started || hasFluidValue(prevTo)) {
2496
+ anim.values = node.getPayload();
2497
+ anim.toValues = hasFluidValue(to) ? null : goalType == AnimatedString ? [1] : toArray(goal);
2498
+ }
2499
+
2500
+ if (anim.immediate != immediate) {
2501
+ anim.immediate = immediate;
2502
+
2503
+ if (!immediate && !reset) {
2504
+ this._set(prevTo);
2505
+ }
2506
+ }
2507
+
2508
+ if (started) {
2509
+ const {
2510
+ onRest
2511
+ } = anim;
2512
+ each(ACTIVE_EVENTS, type => mergeActiveFn(this, props, type));
2513
+ const result = getFinishedResult(this, checkFinished(this, prevTo));
2514
+ flushCalls(this._pendingCalls, result);
2515
+
2516
+ this._pendingCalls.add(resolve);
2517
+
2518
+ if (anim.changed) raf.batchedUpdates(() => {
2519
+ anim.changed = !reset;
2520
+ onRest == null ? void 0 : onRest(result, this);
2521
+
2522
+ if (reset) {
2523
+ callProp(defaultProps.onRest, result);
2524
+ } else {
2525
+ anim.onStart == null ? void 0 : anim.onStart(result, this);
2526
+ }
2527
+ });
2528
+ }
2529
+ }
2530
+
2531
+ if (reset) {
2532
+ this._set(value);
2533
+ }
2534
+
2535
+ if (hasAsyncTo) {
2536
+ resolve(runAsync(props.to, props, this._state, this));
2537
+ } else if (started) {
2538
+ this._start();
2539
+ } else if (isAnimating(this) && !hasToChanged) {
2540
+ this._pendingCalls.add(resolve);
2541
+ } else {
2542
+ resolve(getNoopResult(value));
2543
+ }
2544
+ }
2545
+
2546
+ _focus(value) {
2547
+ const anim = this.animation;
2548
+
2549
+ if (value !== anim.to) {
2550
+ if (getFluidObservers(this)) {
2551
+ this._detach();
2552
+ }
2553
+
2554
+ anim.to = value;
2555
+
2556
+ if (getFluidObservers(this)) {
2557
+ this._attach();
2558
+ }
2559
+ }
2560
+ }
2561
+
2562
+ _attach() {
2563
+ let priority = 0;
2564
+ const {
2565
+ to
2566
+ } = this.animation;
2567
+
2568
+ if (hasFluidValue(to)) {
2569
+ addFluidObserver(to, this);
2570
+
2571
+ if (isFrameValue(to)) {
2572
+ priority = to.priority + 1;
2573
+ }
2574
+ }
2575
+
2576
+ this.priority = priority;
2577
+ }
2578
+
2579
+ _detach() {
2580
+ const {
2581
+ to
2582
+ } = this.animation;
2583
+
2584
+ if (hasFluidValue(to)) {
2585
+ removeFluidObserver(to, this);
2586
+ }
2587
+ }
2588
+
2589
+ _set(arg, idle = true) {
2590
+ const value = getFluidValue(arg);
2591
+
2592
+ if (!is.und(value)) {
2593
+ const oldNode = getAnimated(this);
2594
+
2595
+ if (!oldNode || !isEqual(value, oldNode.getValue())) {
2596
+ const nodeType = getAnimatedType(value);
2597
+
2598
+ if (!oldNode || oldNode.constructor != nodeType) {
2599
+ setAnimated(this, nodeType.create(value));
2600
+ } else {
2601
+ oldNode.setValue(value);
2602
+ }
2603
+
2604
+ if (oldNode) {
2605
+ raf.batchedUpdates(() => {
2606
+ this._onChange(value, idle);
2607
+ });
2608
+ }
2609
+ }
2610
+ }
2611
+
2612
+ return getAnimated(this);
2613
+ }
2614
+
2615
+ _onStart() {
2616
+ const anim = this.animation;
2617
+
2618
+ if (!anim.changed) {
2619
+ anim.changed = true;
2620
+ sendEvent(this, 'onStart', getFinishedResult(this, checkFinished(this, anim.to)), this);
2621
+ }
2622
+ }
2623
+
2624
+ _onChange(value, idle) {
2625
+ if (!idle) {
2626
+ this._onStart();
2627
+
2628
+ callProp(this.animation.onChange, value, this);
2629
+ }
2630
+
2631
+ callProp(this.defaultProps.onChange, value, this);
2632
+
2633
+ super._onChange(value, idle);
2634
+ }
2635
+
2636
+ _start() {
2637
+ const anim = this.animation;
2638
+ getAnimated(this).reset(getFluidValue(anim.to));
2639
+
2640
+ if (!anim.immediate) {
2641
+ anim.fromValues = anim.values.map(node => node.lastPosition);
2642
+ }
2643
+
2644
+ if (!isAnimating(this)) {
2645
+ setActiveBit(this, true);
2646
+
2647
+ if (!isPaused(this)) {
2648
+ this._resume();
2649
+ }
2650
+ }
2651
+ }
2652
+
2653
+ _resume() {
2654
+ if (globals.skipAnimation) {
2655
+ this.finish();
2656
+ } else {
2657
+ frameLoop.start(this);
2658
+ }
2659
+ }
2660
+
2661
+ _stop(goal, cancel) {
2662
+ if (isAnimating(this)) {
2663
+ setActiveBit(this, false);
2664
+ const anim = this.animation;
2665
+ each(anim.values, node => {
2666
+ node.done = true;
2667
+ });
2668
+
2669
+ if (anim.toValues) {
2670
+ anim.onChange = anim.onPause = anim.onResume = undefined;
2671
+ }
2672
+
2673
+ callFluidObservers(this, {
2674
+ type: 'idle',
2675
+ parent: this
2676
+ });
2677
+ const result = cancel ? getCancelledResult(this.get()) : getFinishedResult(this.get(), checkFinished(this, goal != null ? goal : anim.to));
2678
+ flushCalls(this._pendingCalls, result);
2679
+
2680
+ if (anim.changed) {
2681
+ anim.changed = false;
2682
+ sendEvent(this, 'onRest', result, this);
2683
+ }
2684
+ }
2685
+ }
2686
+
2687
+ }
2688
+
2689
+ function checkFinished(target, to) {
2690
+ const goal = computeGoal(to);
2691
+ const value = computeGoal(target.get());
2692
+ return isEqual(value, goal);
2693
+ }
2694
+
2695
+ function createLoopUpdate(props, loop = props.loop, to = props.to) {
2696
+ let loopRet = callProp(loop);
2697
+
2698
+ if (loopRet) {
2699
+ const overrides = loopRet !== true && inferTo(loopRet);
2700
+ const reverse = (overrides || props).reverse;
2701
+ const reset = !overrides || overrides.reset;
2702
+ return createUpdate(_extends({}, props, {
2703
+ loop,
2704
+ default: false,
2705
+ pause: undefined,
2706
+ to: !reverse || isAsyncTo(to) ? to : undefined,
2707
+ from: reset ? props.from : undefined,
2708
+ reset
2709
+ }, overrides));
2710
+ }
2711
+ }
2712
+ function createUpdate(props) {
2713
+ const {
2714
+ to,
2715
+ from
2716
+ } = props = inferTo(props);
2717
+ const keys = new Set();
2718
+ if (is.obj(to)) findDefined(to, keys);
2719
+ if (is.obj(from)) findDefined(from, keys);
2720
+ props.keys = keys.size ? Array.from(keys) : null;
2721
+ return props;
2722
+ }
2723
+ function declareUpdate(props) {
2724
+ const update = createUpdate(props);
2725
+
2726
+ if (is.und(update.default)) {
2727
+ update.default = getDefaultProps(update);
2728
+ }
2729
+
2730
+ return update;
2731
+ }
2732
+
2733
+ function findDefined(values, keys) {
2734
+ eachProp(values, (value, key) => value != null && keys.add(key));
2735
+ }
2736
+
2737
+ const ACTIVE_EVENTS = ['onStart', 'onRest', 'onChange', 'onPause', 'onResume'];
2738
+
2739
+ function mergeActiveFn(target, props, type) {
2740
+ target.animation[type] = props[type] !== getDefaultProp(props, type) ? resolveProp(props[type], target.key) : undefined;
2741
+ }
2742
+
2743
+ function sendEvent(target, type, ...args) {
2744
+ var _target$animation$typ, _target$animation, _target$defaultProps$, _target$defaultProps;
2745
+
2746
+ (_target$animation$typ = (_target$animation = target.animation)[type]) == null ? void 0 : _target$animation$typ.call(_target$animation, ...args);
2747
+ (_target$defaultProps$ = (_target$defaultProps = target.defaultProps)[type]) == null ? void 0 : _target$defaultProps$.call(_target$defaultProps, ...args);
2748
+ }
2749
+
2750
+ const BATCHED_EVENTS = ['onStart', 'onChange', 'onRest'];
2751
+ let nextId = 1;
2752
+ class Controller {
2753
+ constructor(props, flush) {
2754
+ this.id = nextId++;
2755
+ this.springs = {};
2756
+ this.queue = [];
2757
+ this.ref = void 0;
2758
+ this._flush = void 0;
2759
+ this._initialProps = void 0;
2760
+ this._lastAsyncId = 0;
2761
+ this._active = new Set();
2762
+ this._changed = new Set();
2763
+ this._started = false;
2764
+ this._item = void 0;
2765
+ this._state = {
2766
+ paused: false,
2767
+ pauseQueue: new Set(),
2768
+ resumeQueue: new Set(),
2769
+ timeouts: new Set()
2770
+ };
2771
+ this._events = {
2772
+ onStart: new Map(),
2773
+ onChange: new Map(),
2774
+ onRest: new Map()
2775
+ };
2776
+ this._onFrame = this._onFrame.bind(this);
2777
+
2778
+ if (flush) {
2779
+ this._flush = flush;
2780
+ }
2781
+
2782
+ if (props) {
2783
+ this.start(_extends({
2784
+ default: true
2785
+ }, props));
2786
+ }
2787
+ }
2788
+
2789
+ get idle() {
2790
+ return !this._state.asyncTo && Object.values(this.springs).every(spring => {
2791
+ return spring.idle && !spring.isDelayed && !spring.isPaused;
2792
+ });
2793
+ }
2794
+
2795
+ get item() {
2796
+ return this._item;
2797
+ }
2798
+
2799
+ set item(item) {
2800
+ this._item = item;
2801
+ }
2802
+
2803
+ get() {
2804
+ const values = {};
2805
+ this.each((spring, key) => values[key] = spring.get());
2806
+ return values;
2807
+ }
2808
+
2809
+ set(values) {
2810
+ for (const key in values) {
2811
+ const value = values[key];
2812
+
2813
+ if (!is.und(value)) {
2814
+ this.springs[key].set(value);
2815
+ }
2816
+ }
2817
+ }
2818
+
2819
+ update(props) {
2820
+ if (props) {
2821
+ this.queue.push(createUpdate(props));
2822
+ }
2823
+
2824
+ return this;
2825
+ }
2826
+
2827
+ start(props) {
2828
+ let {
2829
+ queue
2830
+ } = this;
2831
+
2832
+ if (props) {
2833
+ queue = toArray(props).map(createUpdate);
2834
+ } else {
2835
+ this.queue = [];
2836
+ }
2837
+
2838
+ if (this._flush) {
2839
+ return this._flush(this, queue);
2840
+ }
2841
+
2842
+ prepareKeys(this, queue);
2843
+ return flushUpdateQueue(this, queue);
2844
+ }
2845
+
2846
+ stop(arg, keys) {
2847
+ if (arg !== !!arg) {
2848
+ keys = arg;
2849
+ }
2850
+
2851
+ if (keys) {
2852
+ const springs = this.springs;
2853
+ each(toArray(keys), key => springs[key].stop(!!arg));
2854
+ } else {
2855
+ stopAsync(this._state, this._lastAsyncId);
2856
+ this.each(spring => spring.stop(!!arg));
2857
+ }
2858
+
2859
+ return this;
2860
+ }
2861
+
2862
+ pause(keys) {
2863
+ if (is.und(keys)) {
2864
+ this.start({
2865
+ pause: true
2866
+ });
2867
+ } else {
2868
+ const springs = this.springs;
2869
+ each(toArray(keys), key => springs[key].pause());
2870
+ }
2871
+
2872
+ return this;
2873
+ }
2874
+
2875
+ resume(keys) {
2876
+ if (is.und(keys)) {
2877
+ this.start({
2878
+ pause: false
2879
+ });
2880
+ } else {
2881
+ const springs = this.springs;
2882
+ each(toArray(keys), key => springs[key].resume());
2883
+ }
2884
+
2885
+ return this;
2886
+ }
2887
+
2888
+ each(iterator) {
2889
+ eachProp(this.springs, iterator);
2890
+ }
2891
+
2892
+ _onFrame() {
2893
+ const {
2894
+ onStart,
2895
+ onChange,
2896
+ onRest
2897
+ } = this._events;
2898
+ const active = this._active.size > 0;
2899
+ const changed = this._changed.size > 0;
2900
+
2901
+ if (active && !this._started || changed && !this._started) {
2902
+ this._started = true;
2903
+ flush(onStart, ([onStart, result]) => {
2904
+ result.value = this.get();
2905
+ onStart(result, this, this._item);
2906
+ });
2907
+ }
2908
+
2909
+ const idle = !active && this._started;
2910
+ const values = changed || idle && onRest.size ? this.get() : null;
2911
+
2912
+ if (changed && onChange.size) {
2913
+ flush(onChange, ([onChange, result]) => {
2914
+ result.value = values;
2915
+ onChange(result, this, this._item);
2916
+ });
2917
+ }
2918
+
2919
+ if (idle) {
2920
+ this._started = false;
2921
+ flush(onRest, ([onRest, result]) => {
2922
+ result.value = values;
2923
+ onRest(result, this, this._item);
2924
+ });
2925
+ }
2926
+ }
2927
+
2928
+ eventObserved(event) {
2929
+ if (event.type == 'change') {
2930
+ this._changed.add(event.parent);
2931
+
2932
+ if (!event.idle) {
2933
+ this._active.add(event.parent);
2934
+ }
2935
+ } else if (event.type == 'idle') {
2936
+ this._active.delete(event.parent);
2937
+ } else return;
2938
+
2939
+ raf.onFrame(this._onFrame);
2940
+ }
2941
+
2942
+ }
2943
+ function flushUpdateQueue(ctrl, queue) {
2944
+ return Promise.all(queue.map(props => flushUpdate(ctrl, props))).then(results => getCombinedResult(ctrl, results));
2945
+ }
2946
+ async function flushUpdate(ctrl, props, isLoop) {
2947
+ const {
2948
+ keys,
2949
+ to,
2950
+ from,
2951
+ loop,
2952
+ onRest,
2953
+ onResolve
2954
+ } = props;
2955
+ const defaults = is.obj(props.default) && props.default;
2956
+
2957
+ if (loop) {
2958
+ props.loop = false;
2959
+ }
2960
+
2961
+ if (to === false) props.to = null;
2962
+ if (from === false) props.from = null;
2963
+ const asyncTo = is.arr(to) || is.fun(to) ? to : undefined;
2964
+
2965
+ if (asyncTo) {
2966
+ props.to = undefined;
2967
+ props.onRest = undefined;
2968
+
2969
+ if (defaults) {
2970
+ defaults.onRest = undefined;
2971
+ }
2972
+ } else {
2973
+ each(BATCHED_EVENTS, key => {
2974
+ const handler = props[key];
2975
+
2976
+ if (is.fun(handler)) {
2977
+ const queue = ctrl['_events'][key];
2978
+
2979
+ props[key] = ({
2980
+ finished,
2981
+ cancelled
2982
+ }) => {
2983
+ const result = queue.get(handler);
2984
+
2985
+ if (result) {
2986
+ if (!finished) result.finished = false;
2987
+ if (cancelled) result.cancelled = true;
2988
+ } else {
2989
+ queue.set(handler, {
2990
+ value: null,
2991
+ finished: finished || false,
2992
+ cancelled: cancelled || false
2993
+ });
2994
+ }
2995
+ };
2996
+
2997
+ if (defaults) {
2998
+ defaults[key] = props[key];
2999
+ }
3000
+ }
3001
+ });
3002
+ }
3003
+
3004
+ const state = ctrl['_state'];
3005
+
3006
+ if (props.pause === !state.paused) {
3007
+ state.paused = props.pause;
3008
+ flushCalls(props.pause ? state.pauseQueue : state.resumeQueue);
3009
+ } else if (state.paused) {
3010
+ props.pause = true;
3011
+ }
3012
+
3013
+ const promises = (keys || Object.keys(ctrl.springs)).map(key => ctrl.springs[key].start(props));
3014
+ const cancel = props.cancel === true || getDefaultProp(props, 'cancel') === true;
3015
+
3016
+ if (asyncTo || cancel && state.asyncId) {
3017
+ promises.push(scheduleProps(++ctrl['_lastAsyncId'], {
3018
+ props,
3019
+ state,
3020
+ actions: {
3021
+ pause: noop,
3022
+ resume: noop,
3023
+
3024
+ start(props, resolve) {
3025
+ if (cancel) {
3026
+ stopAsync(state, ctrl['_lastAsyncId']);
3027
+ resolve(getCancelledResult(ctrl));
3028
+ } else {
3029
+ props.onRest = onRest;
3030
+ resolve(runAsync(asyncTo, props, state, ctrl));
3031
+ }
3032
+ }
3033
+
3034
+ }
3035
+ }));
3036
+ }
3037
+
3038
+ if (state.paused) {
3039
+ await new Promise(resume => {
3040
+ state.resumeQueue.add(resume);
3041
+ });
3042
+ }
3043
+
3044
+ const result = getCombinedResult(ctrl, await Promise.all(promises));
3045
+
3046
+ if (loop && result.finished && !(isLoop && result.noop)) {
3047
+ const nextProps = createLoopUpdate(props, loop, to);
3048
+
3049
+ if (nextProps) {
3050
+ prepareKeys(ctrl, [nextProps]);
3051
+ return flushUpdate(ctrl, nextProps, true);
3052
+ }
3053
+ }
3054
+
3055
+ if (onResolve) {
3056
+ raf.batchedUpdates(() => onResolve(result, ctrl, ctrl.item));
3057
+ }
3058
+
3059
+ return result;
3060
+ }
3061
+ function getSprings(ctrl, props) {
3062
+ const springs = _extends({}, ctrl.springs);
3063
+
3064
+ if (props) {
3065
+ each(toArray(props), props => {
3066
+ if (is.und(props.keys)) {
3067
+ props = createUpdate(props);
3068
+ }
3069
+
3070
+ if (!is.obj(props.to)) {
3071
+ props = _extends({}, props, {
3072
+ to: undefined
3073
+ });
3074
+ }
3075
+
3076
+ prepareSprings(springs, props, key => {
3077
+ return createSpring(key);
3078
+ });
3079
+ });
3080
+ }
3081
+
3082
+ setSprings(ctrl, springs);
3083
+ return springs;
3084
+ }
3085
+ function setSprings(ctrl, springs) {
3086
+ eachProp(springs, (spring, key) => {
3087
+ if (!ctrl.springs[key]) {
3088
+ ctrl.springs[key] = spring;
3089
+ addFluidObserver(spring, ctrl);
3090
+ }
3091
+ });
3092
+ }
3093
+
3094
+ function createSpring(key, observer) {
3095
+ const spring = new SpringValue();
3096
+ spring.key = key;
3097
+
3098
+ if (observer) {
3099
+ addFluidObserver(spring, observer);
3100
+ }
3101
+
3102
+ return spring;
3103
+ }
3104
+
3105
+ function prepareSprings(springs, props, create) {
3106
+ if (props.keys) {
3107
+ each(props.keys, key => {
3108
+ const spring = springs[key] || (springs[key] = create(key));
3109
+ spring['_prepareNode'](props);
3110
+ });
3111
+ }
3112
+ }
3113
+
3114
+ function prepareKeys(ctrl, queue) {
3115
+ each(queue, props => {
3116
+ prepareSprings(ctrl.springs, props, key => {
3117
+ return createSpring(key, ctrl);
3118
+ });
3119
+ });
3120
+ }
3121
+
3122
+ function _objectWithoutPropertiesLoose$1(source, excluded) {
3123
+ if (source == null) return {};
3124
+ var target = {};
3125
+ var sourceKeys = Object.keys(source);
3126
+ var key, i;
3127
+
3128
+ for (i = 0; i < sourceKeys.length; i++) {
3129
+ key = sourceKeys[i];
3130
+ if (excluded.indexOf(key) >= 0) continue;
3131
+ target[key] = source[key];
3132
+ }
3133
+
3134
+ return target;
3135
+ }
3136
+
3137
+ const _excluded$3 = ["children"];
3138
+ const SpringContext = _ref => {
3139
+ let {
3140
+ children
3141
+ } = _ref,
3142
+ props = _objectWithoutPropertiesLoose$1(_ref, _excluded$3);
3143
+
3144
+ const inherited = React.useContext(ctx);
3145
+ const pause = props.pause || !!inherited.pause,
3146
+ immediate = props.immediate || !!inherited.immediate;
3147
+ props = useMemoOne(() => ({
3148
+ pause,
3149
+ immediate
3150
+ }), [pause, immediate]);
3151
+ const {
3152
+ Provider
3153
+ } = ctx;
3154
+ return React__namespace.createElement(Provider, {
3155
+ value: props
3156
+ }, children);
3157
+ };
3158
+ const ctx = makeContext(SpringContext, {});
3159
+ SpringContext.Provider = ctx.Provider;
3160
+ SpringContext.Consumer = ctx.Consumer;
3161
+
3162
+ function makeContext(target, init) {
3163
+ Object.assign(target, React__namespace.createContext(init));
3164
+ target.Provider._context = target;
3165
+ target.Consumer._context = target;
3166
+ return target;
3167
+ }
3168
+
3169
+ const SpringRef = () => {
3170
+ const current = [];
3171
+
3172
+ const SpringRef = function SpringRef(props) {
3173
+ deprecateDirectCall();
3174
+ const results = [];
3175
+ each(current, (ctrl, i) => {
3176
+ if (is.und(props)) {
3177
+ results.push(ctrl.start());
3178
+ } else {
3179
+ const update = _getProps(props, ctrl, i);
3180
+
3181
+ if (update) {
3182
+ results.push(ctrl.start(update));
3183
+ }
3184
+ }
3185
+ });
3186
+ return results;
3187
+ };
3188
+
3189
+ SpringRef.current = current;
3190
+
3191
+ SpringRef.add = function (ctrl) {
3192
+ if (!current.includes(ctrl)) {
3193
+ current.push(ctrl);
3194
+ }
3195
+ };
3196
+
3197
+ SpringRef.delete = function (ctrl) {
3198
+ const i = current.indexOf(ctrl);
3199
+ if (~i) current.splice(i, 1);
3200
+ };
3201
+
3202
+ SpringRef.pause = function () {
3203
+ each(current, ctrl => ctrl.pause(...arguments));
3204
+ return this;
3205
+ };
3206
+
3207
+ SpringRef.resume = function () {
3208
+ each(current, ctrl => ctrl.resume(...arguments));
3209
+ return this;
3210
+ };
3211
+
3212
+ SpringRef.set = function (values) {
3213
+ each(current, ctrl => ctrl.set(values));
3214
+ };
3215
+
3216
+ SpringRef.start = function (props) {
3217
+ const results = [];
3218
+ each(current, (ctrl, i) => {
3219
+ if (is.und(props)) {
3220
+ results.push(ctrl.start());
3221
+ } else {
3222
+ const update = this._getProps(props, ctrl, i);
3223
+
3224
+ if (update) {
3225
+ results.push(ctrl.start(update));
3226
+ }
3227
+ }
3228
+ });
3229
+ return results;
3230
+ };
3231
+
3232
+ SpringRef.stop = function () {
3233
+ each(current, ctrl => ctrl.stop(...arguments));
3234
+ return this;
3235
+ };
3236
+
3237
+ SpringRef.update = function (props) {
3238
+ each(current, (ctrl, i) => ctrl.update(this._getProps(props, ctrl, i)));
3239
+ return this;
3240
+ };
3241
+
3242
+ const _getProps = function _getProps(arg, ctrl, index) {
3243
+ return is.fun(arg) ? arg(index, ctrl) : arg;
3244
+ };
3245
+
3246
+ SpringRef._getProps = _getProps;
3247
+ return SpringRef;
3248
+ };
3249
+
3250
+ function useSprings(length, props, deps) {
3251
+ const propsFn = is.fun(props) && props;
3252
+ if (propsFn && !deps) deps = [];
3253
+ const ref = React.useMemo(() => propsFn || arguments.length == 3 ? SpringRef() : void 0, []);
3254
+ const layoutId = React.useRef(0);
3255
+ const forceUpdate = useForceUpdate();
3256
+ const state = React.useMemo(() => ({
3257
+ ctrls: [],
3258
+ queue: [],
3259
+
3260
+ flush(ctrl, updates) {
3261
+ const springs = getSprings(ctrl, updates);
3262
+ const canFlushSync = layoutId.current > 0 && !state.queue.length && !Object.keys(springs).some(key => !ctrl.springs[key]);
3263
+ return canFlushSync ? flushUpdateQueue(ctrl, updates) : new Promise(resolve => {
3264
+ setSprings(ctrl, springs);
3265
+ state.queue.push(() => {
3266
+ resolve(flushUpdateQueue(ctrl, updates));
3267
+ });
3268
+ forceUpdate();
3269
+ });
3270
+ }
3271
+
3272
+ }), []);
3273
+ const ctrls = React.useRef([...state.ctrls]);
3274
+ const updates = [];
3275
+ const prevLength = usePrev(length) || 0;
3276
+ React.useMemo(() => {
3277
+ each(ctrls.current.slice(length, prevLength), ctrl => {
3278
+ detachRefs(ctrl, ref);
3279
+ ctrl.stop(true);
3280
+ });
3281
+ ctrls.current.length = length;
3282
+ declareUpdates(prevLength, length);
3283
+ }, [length]);
3284
+ React.useMemo(() => {
3285
+ declareUpdates(0, Math.min(prevLength, length));
3286
+ }, deps);
3287
+
3288
+ function declareUpdates(startIndex, endIndex) {
3289
+ for (let i = startIndex; i < endIndex; i++) {
3290
+ const ctrl = ctrls.current[i] || (ctrls.current[i] = new Controller(null, state.flush));
3291
+ const update = propsFn ? propsFn(i, ctrl) : props[i];
3292
+
3293
+ if (update) {
3294
+ updates[i] = declareUpdate(update);
3295
+ }
3296
+ }
3297
+ }
3298
+
3299
+ const springs = ctrls.current.map((ctrl, i) => getSprings(ctrl, updates[i]));
3300
+ const context = React.useContext(SpringContext);
3301
+ const prevContext = usePrev(context);
3302
+ const hasContext = context !== prevContext && hasProps(context);
3303
+ useIsomorphicLayoutEffect(() => {
3304
+ layoutId.current++;
3305
+ state.ctrls = ctrls.current;
3306
+ const {
3307
+ queue
3308
+ } = state;
3309
+
3310
+ if (queue.length) {
3311
+ state.queue = [];
3312
+ each(queue, cb => cb());
3313
+ }
3314
+
3315
+ each(ctrls.current, (ctrl, i) => {
3316
+ ref == null ? void 0 : ref.add(ctrl);
3317
+
3318
+ if (hasContext) {
3319
+ ctrl.start({
3320
+ default: context
3321
+ });
3322
+ }
3323
+
3324
+ const update = updates[i];
3325
+
3326
+ if (update) {
3327
+ replaceRef(ctrl, update.ref);
3328
+
3329
+ if (ctrl.ref) {
3330
+ ctrl.queue.push(update);
3331
+ } else {
3332
+ ctrl.start(update);
3333
+ }
3334
+ }
3335
+ });
3336
+ });
3337
+ useOnce(() => () => {
3338
+ each(state.ctrls, ctrl => ctrl.stop(true));
3339
+ });
3340
+ const values = springs.map(x => _extends({}, x));
3341
+ return ref ? [values, ref] : values;
3342
+ }
3343
+
3344
+ function useSpring(props, deps) {
3345
+ const isFn = is.fun(props);
3346
+ const [[values], ref] = useSprings(1, isFn ? props : [props], isFn ? deps || [] : deps);
3347
+ return isFn || arguments.length == 2 ? [values, ref] : values;
3348
+ }
3349
+
3350
+ let TransitionPhase;
3351
+
3352
+ (function (TransitionPhase) {
3353
+ TransitionPhase["MOUNT"] = "mount";
3354
+ TransitionPhase["ENTER"] = "enter";
3355
+ TransitionPhase["UPDATE"] = "update";
3356
+ TransitionPhase["LEAVE"] = "leave";
3357
+ })(TransitionPhase || (TransitionPhase = {}));
3358
+
3359
+ class Interpolation extends FrameValue {
3360
+ constructor(source, args) {
3361
+ super();
3362
+ this.key = void 0;
3363
+ this.idle = true;
3364
+ this.calc = void 0;
3365
+ this._active = new Set();
3366
+ this.source = source;
3367
+ this.calc = createInterpolator(...args);
3368
+
3369
+ const value = this._get();
3370
+
3371
+ const nodeType = getAnimatedType(value);
3372
+ setAnimated(this, nodeType.create(value));
3373
+ }
3374
+
3375
+ advance(_dt) {
3376
+ const value = this._get();
3377
+
3378
+ const oldValue = this.get();
3379
+
3380
+ if (!isEqual(value, oldValue)) {
3381
+ getAnimated(this).setValue(value);
3382
+
3383
+ this._onChange(value, this.idle);
3384
+ }
3385
+
3386
+ if (!this.idle && checkIdle(this._active)) {
3387
+ becomeIdle(this);
3388
+ }
3389
+ }
3390
+
3391
+ _get() {
3392
+ const inputs = is.arr(this.source) ? this.source.map(getFluidValue) : toArray(getFluidValue(this.source));
3393
+ return this.calc(...inputs);
3394
+ }
3395
+
3396
+ _start() {
3397
+ if (this.idle && !checkIdle(this._active)) {
3398
+ this.idle = false;
3399
+ each(getPayload(this), node => {
3400
+ node.done = false;
3401
+ });
3402
+
3403
+ if (globals.skipAnimation) {
3404
+ raf.batchedUpdates(() => this.advance());
3405
+ becomeIdle(this);
3406
+ } else {
3407
+ frameLoop.start(this);
3408
+ }
3409
+ }
3410
+ }
3411
+
3412
+ _attach() {
3413
+ let priority = 1;
3414
+ each(toArray(this.source), source => {
3415
+ if (hasFluidValue(source)) {
3416
+ addFluidObserver(source, this);
3417
+ }
3418
+
3419
+ if (isFrameValue(source)) {
3420
+ if (!source.idle) {
3421
+ this._active.add(source);
3422
+ }
3423
+
3424
+ priority = Math.max(priority, source.priority + 1);
3425
+ }
3426
+ });
3427
+ this.priority = priority;
3428
+
3429
+ this._start();
3430
+ }
3431
+
3432
+ _detach() {
3433
+ each(toArray(this.source), source => {
3434
+ if (hasFluidValue(source)) {
3435
+ removeFluidObserver(source, this);
3436
+ }
3437
+ });
3438
+
3439
+ this._active.clear();
3440
+
3441
+ becomeIdle(this);
3442
+ }
3443
+
3444
+ eventObserved(event) {
3445
+ if (event.type == 'change') {
3446
+ if (event.idle) {
3447
+ this.advance();
3448
+ } else {
3449
+ this._active.add(event.parent);
3450
+
3451
+ this._start();
3452
+ }
3453
+ } else if (event.type == 'idle') {
3454
+ this._active.delete(event.parent);
3455
+ } else if (event.type == 'priority') {
3456
+ this.priority = toArray(this.source).reduce((highest, parent) => Math.max(highest, (isFrameValue(parent) ? parent.priority : 0) + 1), 0);
3457
+ }
3458
+ }
3459
+
3460
+ }
3461
+
3462
+ function isIdle(source) {
3463
+ return source.idle !== false;
3464
+ }
3465
+
3466
+ function checkIdle(active) {
3467
+ return !active.size || Array.from(active).every(isIdle);
3468
+ }
3469
+
3470
+ function becomeIdle(self) {
3471
+ if (!self.idle) {
3472
+ self.idle = true;
3473
+ each(getPayload(self), node => {
3474
+ node.done = true;
3475
+ });
3476
+ callFluidObservers(self, {
3477
+ type: 'idle',
3478
+ parent: self
3479
+ });
3480
+ }
3481
+ }
3482
+
3483
+ globals.assign({
3484
+ createStringInterpolator,
3485
+ to: (source, args) => new Interpolation(source, args)
3486
+ });
3487
+
3488
+ function _objectWithoutPropertiesLoose(source, excluded) {
3489
+ if (source == null) return {};
3490
+ var target = {};
3491
+ var sourceKeys = Object.keys(source);
3492
+ var key, i;
3493
+
3494
+ for (i = 0; i < sourceKeys.length; i++) {
3495
+ key = sourceKeys[i];
3496
+ if (excluded.indexOf(key) >= 0) continue;
3497
+ target[key] = source[key];
3498
+ }
3499
+
3500
+ return target;
3501
+ }
3502
+
3503
+ const _excluded$2 = ["style", "children", "scrollTop", "scrollLeft"];
3504
+ const isCustomPropRE = /^--/;
3505
+
3506
+ function dangerousStyleValue(name, value) {
3507
+ if (value == null || typeof value === 'boolean' || value === '') return '';
3508
+ if (typeof value === 'number' && value !== 0 && !isCustomPropRE.test(name) && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) return value + 'px';
3509
+ return ('' + value).trim();
3510
+ }
3511
+
3512
+ const attributeCache = {};
3513
+ function applyAnimatedValues(instance, props) {
3514
+ if (!instance.nodeType || !instance.setAttribute) {
3515
+ return false;
3516
+ }
3517
+
3518
+ const isFilterElement = instance.nodeName === 'filter' || instance.parentNode && instance.parentNode.nodeName === 'filter';
3519
+
3520
+ const _ref = props,
3521
+ {
3522
+ style,
3523
+ children,
3524
+ scrollTop,
3525
+ scrollLeft
3526
+ } = _ref,
3527
+ attributes = _objectWithoutPropertiesLoose(_ref, _excluded$2);
3528
+
3529
+ const values = Object.values(attributes);
3530
+ const names = Object.keys(attributes).map(name => isFilterElement || instance.hasAttribute(name) ? name : attributeCache[name] || (attributeCache[name] = name.replace(/([A-Z])/g, n => '-' + n.toLowerCase())));
3531
+
3532
+ if (children !== void 0) {
3533
+ instance.textContent = children;
3534
+ }
3535
+
3536
+ for (let name in style) {
3537
+ if (style.hasOwnProperty(name)) {
3538
+ const value = dangerousStyleValue(name, style[name]);
3539
+
3540
+ if (isCustomPropRE.test(name)) {
3541
+ instance.style.setProperty(name, value);
3542
+ } else {
3543
+ instance.style[name] = value;
3544
+ }
3545
+ }
3546
+ }
3547
+
3548
+ names.forEach((name, i) => {
3549
+ instance.setAttribute(name, values[i]);
3550
+ });
3551
+
3552
+ if (scrollTop !== void 0) {
3553
+ instance.scrollTop = scrollTop;
3554
+ }
3555
+
3556
+ if (scrollLeft !== void 0) {
3557
+ instance.scrollLeft = scrollLeft;
3558
+ }
3559
+ }
3560
+ let isUnitlessNumber = {
3561
+ animationIterationCount: true,
3562
+ borderImageOutset: true,
3563
+ borderImageSlice: true,
3564
+ borderImageWidth: true,
3565
+ boxFlex: true,
3566
+ boxFlexGroup: true,
3567
+ boxOrdinalGroup: true,
3568
+ columnCount: true,
3569
+ columns: true,
3570
+ flex: true,
3571
+ flexGrow: true,
3572
+ flexPositive: true,
3573
+ flexShrink: true,
3574
+ flexNegative: true,
3575
+ flexOrder: true,
3576
+ gridRow: true,
3577
+ gridRowEnd: true,
3578
+ gridRowSpan: true,
3579
+ gridRowStart: true,
3580
+ gridColumn: true,
3581
+ gridColumnEnd: true,
3582
+ gridColumnSpan: true,
3583
+ gridColumnStart: true,
3584
+ fontWeight: true,
3585
+ lineClamp: true,
3586
+ lineHeight: true,
3587
+ opacity: true,
3588
+ order: true,
3589
+ orphans: true,
3590
+ tabSize: true,
3591
+ widows: true,
3592
+ zIndex: true,
3593
+ zoom: true,
3594
+ fillOpacity: true,
3595
+ floodOpacity: true,
3596
+ stopOpacity: true,
3597
+ strokeDasharray: true,
3598
+ strokeDashoffset: true,
3599
+ strokeMiterlimit: true,
3600
+ strokeOpacity: true,
3601
+ strokeWidth: true
3602
+ };
3603
+
3604
+ const prefixKey = (prefix, key) => prefix + key.charAt(0).toUpperCase() + key.substring(1);
3605
+
3606
+ const prefixes = ['Webkit', 'Ms', 'Moz', 'O'];
3607
+ isUnitlessNumber = Object.keys(isUnitlessNumber).reduce((acc, prop) => {
3608
+ prefixes.forEach(prefix => acc[prefixKey(prefix, prop)] = acc[prop]);
3609
+ return acc;
3610
+ }, isUnitlessNumber);
3611
+
3612
+ const _excluded$1 = ["x", "y", "z"];
3613
+ const domTransforms = /^(matrix|translate|scale|rotate|skew)/;
3614
+ const pxTransforms = /^(translate)/;
3615
+ const degTransforms = /^(rotate|skew)/;
3616
+
3617
+ const addUnit = (value, unit) => is.num(value) && value !== 0 ? value + unit : value;
3618
+
3619
+ const isValueIdentity = (value, id) => is.arr(value) ? value.every(v => isValueIdentity(v, id)) : is.num(value) ? value === id : parseFloat(value) === id;
3620
+
3621
+ class AnimatedStyle extends AnimatedObject {
3622
+ constructor(_ref) {
3623
+ let {
3624
+ x,
3625
+ y,
3626
+ z
3627
+ } = _ref,
3628
+ style = _objectWithoutPropertiesLoose(_ref, _excluded$1);
3629
+
3630
+ const inputs = [];
3631
+ const transforms = [];
3632
+
3633
+ if (x || y || z) {
3634
+ inputs.push([x || 0, y || 0, z || 0]);
3635
+ transforms.push(xyz => [`translate3d(${xyz.map(v => addUnit(v, 'px')).join(',')})`, isValueIdentity(xyz, 0)]);
3636
+ }
3637
+
3638
+ eachProp(style, (value, key) => {
3639
+ if (key === 'transform') {
3640
+ inputs.push([value || '']);
3641
+ transforms.push(transform => [transform, transform === '']);
3642
+ } else if (domTransforms.test(key)) {
3643
+ delete style[key];
3644
+ if (is.und(value)) return;
3645
+ const unit = pxTransforms.test(key) ? 'px' : degTransforms.test(key) ? 'deg' : '';
3646
+ inputs.push(toArray(value));
3647
+ transforms.push(key === 'rotate3d' ? ([x, y, z, deg]) => [`rotate3d(${x},${y},${z},${addUnit(deg, unit)})`, isValueIdentity(deg, 0)] : input => [`${key}(${input.map(v => addUnit(v, unit)).join(',')})`, isValueIdentity(input, key.startsWith('scale') ? 1 : 0)]);
3648
+ }
3649
+ });
3650
+
3651
+ if (inputs.length) {
3652
+ style.transform = new FluidTransform(inputs, transforms);
3653
+ }
3654
+
3655
+ super(style);
3656
+ }
3657
+
3658
+ }
3659
+
3660
+ class FluidTransform extends FluidValue {
3661
+ constructor(inputs, transforms) {
3662
+ super();
3663
+ this._value = null;
3664
+ this.inputs = inputs;
3665
+ this.transforms = transforms;
3666
+ }
3667
+
3668
+ get() {
3669
+ return this._value || (this._value = this._get());
3670
+ }
3671
+
3672
+ _get() {
3673
+ let transform = '';
3674
+ let identity = true;
3675
+ each(this.inputs, (input, i) => {
3676
+ const arg1 = getFluidValue(input[0]);
3677
+ const [t, id] = this.transforms[i](is.arr(arg1) ? arg1 : input.map(getFluidValue));
3678
+ transform += ' ' + t;
3679
+ identity = identity && id;
3680
+ });
3681
+ return identity ? 'none' : transform;
3682
+ }
3683
+
3684
+ observerAdded(count) {
3685
+ if (count == 1) each(this.inputs, input => each(input, value => hasFluidValue(value) && addFluidObserver(value, this)));
3686
+ }
3687
+
3688
+ observerRemoved(count) {
3689
+ if (count == 0) each(this.inputs, input => each(input, value => hasFluidValue(value) && removeFluidObserver(value, this)));
3690
+ }
3691
+
3692
+ eventObserved(event) {
3693
+ if (event.type == 'change') {
3694
+ this._value = null;
3695
+ }
3696
+
3697
+ callFluidObservers(this, event);
3698
+ }
3699
+
3700
+ }
3701
+
3702
+ const primitives = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', 'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'];
3703
+
3704
+ const _excluded = ["scrollTop", "scrollLeft"];
3705
+ globals.assign({
3706
+ batchedUpdates: reactDom.unstable_batchedUpdates,
3707
+ createStringInterpolator,
3708
+ colors
3709
+ });
3710
+ createHost(primitives, {
3711
+ applyAnimatedValues,
3712
+ createAnimatedStyle: style => new AnimatedStyle(style),
3713
+ getComponentProps: _ref => {
3714
+ let props = _objectWithoutPropertiesLoose(_ref, _excluded);
3715
+
3716
+ return props;
3717
+ }
3718
+ });
3719
+
3720
+ const eventLabel = 'RSC::Event';
3721
+ function useEventsModule() {
3722
+ const targetEvent = React.useRef(null);
3723
+ React.useEffect(() => {
3724
+ targetEvent.current = document.createElement('div');
3725
+ }, []);
3726
+ function useListenToCustomEvent(eventHandler) {
3727
+ React.useEffect(() => {
3728
+ function handleEvent(event) {
3729
+ eventHandler(event.detail);
3730
+ }
3731
+ if (targetEvent.current) {
3732
+ // @ts-ignore
3733
+ targetEvent.current.addEventListener(eventLabel, handleEvent, false);
3734
+ return () => {
3735
+ var _a;
3736
+ // @ts-ignore
3737
+ (_a = targetEvent.current) === null || _a === void 0 ? void 0 : _a.removeEventListener(eventLabel, handleEvent, false);
3738
+ };
3739
+ }
3740
+ }, []);
3741
+ }
3742
+ function emitEvent(event) {
3743
+ if (targetEvent.current) {
3744
+ const newEvent = new CustomEvent(eventLabel, {
3745
+ detail: event,
3746
+ });
3747
+ targetEvent.current.dispatchEvent(newEvent);
3748
+ }
3749
+ }
3750
+ return {
3751
+ useListenToCustomEvent,
3752
+ emitEvent,
3753
+ };
3754
+ }
3755
+
3756
+ function useFullscreenModule({ mainCarouselWrapperRef, emitEvent, handleResize, }) {
3757
+ const isFullscreen = React.useRef(false);
3758
+ React.useEffect(() => {
3759
+ function handleFullscreenChange() {
3760
+ if (document.fullscreenElement) {
3761
+ setIsFullscreen(true);
3762
+ emitEvent({
3763
+ eventName: 'onFullscreenChange',
3764
+ isFullscreen: true,
3765
+ });
3766
+ handleResize && handleResize();
3767
+ }
3768
+ if (!document.fullscreenElement) {
3769
+ setIsFullscreen(false);
3770
+ emitEvent({
3771
+ eventName: 'onFullscreenChange',
3772
+ isFullscreen: false,
3773
+ });
3774
+ handleResize && handleResize();
3775
+ }
3776
+ }
3777
+ if (screenfull.isEnabled) {
3778
+ screenfull.on('change', handleFullscreenChange);
3779
+ return () => {
3780
+ if (screenfull.isEnabled) {
3781
+ screenfull.off('change', handleFullscreenChange);
3782
+ }
3783
+ };
3784
+ }
3785
+ }, []);
3786
+ function setIsFullscreen(_isFullscreen) {
3787
+ isFullscreen.current = _isFullscreen;
3788
+ }
3789
+ function getIsFullscreen() {
3790
+ return isFullscreen.current;
3791
+ }
3792
+ function enterFullscreen(elementRef) {
3793
+ if (screenfull.isEnabled) {
3794
+ screenfull.request((elementRef || mainCarouselWrapperRef.current));
3795
+ }
3796
+ }
3797
+ function exitFullscreen() {
3798
+ screenfull.isEnabled && screenfull.exit();
3799
+ }
3800
+ return {
3801
+ enterFullscreen,
3802
+ exitFullscreen,
3803
+ getIsFullscreen,
3804
+ };
3805
+ }
3806
+
3807
+ function isInViewport(el) {
3808
+ const rect = el.getBoundingClientRect();
3809
+ return (rect.top >= 0 &&
3810
+ rect.left >= 0 &&
3811
+ rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
3812
+ rect.right <= (window.innerWidth || document.documentElement.clientWidth));
3813
+ }
3814
+ function useThumbsModule({ thumbsSlideAxis = 'x', withThumbs = false, prepareThumbsData, items, }) {
3815
+ const wrapperRef = React.useRef(null);
3816
+ const [spring, setSpring] = useSpring(() => ({
3817
+ val: 0,
3818
+ }));
3819
+ function getTotalScrollValue() {
3820
+ var _a;
3821
+ return Math.round(Number((_a = wrapperRef.current) === null || _a === void 0 ? void 0 : _a[thumbsSlideAxis === 'x' ? 'scrollWidth' : 'scrollHeight']) -
3822
+ wrapperRef.current.getBoundingClientRect()[thumbsSlideAxis === 'x' ? 'width' : 'height']);
3823
+ }
3824
+ function handleScroll(activeItem) {
3825
+ var _a, _b;
3826
+ function getThumbNode() {
3827
+ if (wrapperRef.current) {
3828
+ return wrapperRef.current.querySelector(`#thumb-item-${items[activeItem].id}`);
3829
+ }
3830
+ return null;
3831
+ }
3832
+ const thumbNode = getThumbNode();
3833
+ if (thumbNode && wrapperRef.current) {
3834
+ if (!isInViewport(thumbNode)) {
3835
+ const offset = thumbNode.offsetLeft;
3836
+ const val = offset > getTotalScrollValue() ? getTotalScrollValue() : offset;
3837
+ setSpring.start({
3838
+ from: {
3839
+ val: (_b = (_a = wrapperRef.current) === null || _a === void 0 ? void 0 : _a[thumbsSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop']) !== null && _b !== void 0 ? _b : 0,
3840
+ },
3841
+ to: {
3842
+ val,
3843
+ },
3844
+ onChange: ({ value }) => {
3845
+ if (wrapperRef.current) {
3846
+ wrapperRef.current[thumbsSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'] =
3847
+ Math.abs(value.val);
3848
+ }
3849
+ },
3850
+ });
3851
+ }
3852
+ }
3853
+ }
3854
+ function handlePrepareThumbsData() {
3855
+ function getPreparedItems(_items) {
3856
+ return _items.map(i => ({
3857
+ id: i.id,
3858
+ renderThumb: i.renderThumb,
3859
+ }));
3860
+ }
3861
+ if (prepareThumbsData) {
3862
+ return prepareThumbsData(getPreparedItems(items));
3863
+ }
3864
+ return getPreparedItems(items);
3865
+ }
3866
+ const thumbsFragment = withThumbs ? (jsxRuntime.jsx("div", Object.assign({ className: "use-spring-carousel-thumbs-wrapper", ref: wrapperRef, onWheel: () => spring.val.stop(), style: Object.assign({ display: 'flex', flex: '1', position: 'relative', width: '100%', height: '100%', flexDirection: thumbsSlideAxis === 'x' ? 'row' : 'column' }, (thumbsSlideAxis === 'x'
3867
+ ? { overflowX: 'auto' }
3868
+ : {
3869
+ overflowY: 'auto',
3870
+ maxHeight: '100%',
3871
+ })) }, { children: handlePrepareThumbsData().map(({ id, renderThumb }) => {
3872
+ const thumbId = `thumb-item-${id}`;
3873
+ return (jsxRuntime.jsx("div", Object.assign({ id: thumbId, className: "thumb-item" }, { children: renderThumb }), thumbId));
3874
+ }) }))) : null;
3875
+ return {
3876
+ thumbsFragment,
3877
+ handleScroll,
3878
+ };
3879
+ }
3880
+
3881
+ function useSpringCarousel({ items, init = true, withThumbs, thumbsSlideAxis = 'x', itemsPerSlide = 1, slideType = 'fixed', gutter = 0, withLoop = false, startEndGutter = 0, carouselSlideAxis = 'x', disableGestures = false, draggingSlideTreshold: _draggingSlideTreshold, slideWhenThresholdIsReached = false, freeScroll, enableFreeScrollDrag, initialStartingPosition, prepareThumbsData, initialActiveItem = 0, }) {
3882
+ const prevWindowWidth = React.useRef(0);
3883
+ const draggingSlideTreshold = React.useRef(_draggingSlideTreshold !== null && _draggingSlideTreshold !== void 0 ? _draggingSlideTreshold : 0);
3884
+ const slideActionType = React.useRef('initial');
3885
+ const slideModeType = React.useRef('initial');
3886
+ const prevSlidedValue = React.useRef(0);
3887
+ const [spring, setSpring] = useSpring(() => ({
3888
+ val: 0,
3889
+ pause: !init,
3890
+ onChange({ value }) {
3891
+ if (freeScroll && mainCarouselWrapperRef.current) {
3892
+ setStartEndItemReachedOnFreeScroll();
3893
+ if (carouselSlideAxis === 'x') {
3894
+ mainCarouselWrapperRef.current.scrollLeft = Math.abs(value.val);
3895
+ }
3896
+ else {
3897
+ mainCarouselWrapperRef.current.scrollTop = Math.abs(value.val);
3898
+ }
3899
+ }
3900
+ else if (carouselTrackWrapperRef.current) {
3901
+ if (carouselSlideAxis === 'x') {
3902
+ carouselTrackWrapperRef.current.style.transform = `translate3d(${value.val}px, 0px,0px)`;
3903
+ }
3904
+ else {
3905
+ carouselTrackWrapperRef.current.style.transform = `translate3d(0px,${value.val}px,0px)`;
3906
+ }
3907
+ }
3908
+ },
3909
+ }));
3910
+ const activeItem = React.useRef(initialActiveItem);
3911
+ const firstItemReached = React.useRef(initialActiveItem === 0);
3912
+ const lastItemReached = React.useRef(false);
3913
+ const mainCarouselWrapperRef = React.useRef(null);
3914
+ const carouselTrackWrapperRef = React.useRef(null);
3915
+ const getItems = React.useCallback(() => {
3916
+ if (withLoop) {
3917
+ return [
3918
+ ...items.map(i => (Object.assign(Object.assign({}, i), { id: `prev-repeated-item-${i.id}` }))),
3919
+ ...items,
3920
+ ...items.map(i => (Object.assign(Object.assign({}, i), { id: `next-repeated-item-${i.id}` }))),
3921
+ ];
3922
+ }
3923
+ return [...items];
3924
+ }, [items, withLoop]);
3925
+ const internalItems = getItems();
3926
+ const { emitEvent, useListenToCustomEvent } = useEventsModule();
3927
+ const { thumbsFragment, handleScroll } = useThumbsModule({
3928
+ withThumbs: !!withThumbs,
3929
+ thumbsSlideAxis,
3930
+ prepareThumbsData,
3931
+ items: items,
3932
+ });
3933
+ const { enterFullscreen, exitFullscreen, getIsFullscreen } = useFullscreenModule({
3934
+ mainCarouselWrapperRef,
3935
+ emitEvent,
3936
+ handleResize: () => adjustCarouselWrapperPosition(),
3937
+ });
3938
+ function getItemStyles() {
3939
+ if (slideType === 'fixed' && !freeScroll) {
3940
+ return {
3941
+ marginRight: `${gutter}px`,
3942
+ flex: `1 0 calc(100% / ${itemsPerSlide} - ${(gutter * (itemsPerSlide - 1)) / itemsPerSlide}px)`,
3943
+ };
3944
+ }
3945
+ return Object.assign({ marginRight: `${gutter}px` });
3946
+ }
3947
+ function getSlideValue() {
3948
+ var _a;
3949
+ const carouselItem = (_a = mainCarouselWrapperRef.current) === null || _a === void 0 ? void 0 : _a.querySelector('.use-spring-carousel-item');
3950
+ if (!carouselItem) {
3951
+ throw Error('No carousel items available!');
3952
+ }
3953
+ return (carouselItem.getBoundingClientRect()[carouselSlideAxis === 'x' ? 'width' : 'height'] + gutter);
3954
+ }
3955
+ function slideToItem({ from, to, nextActiveItem, immediate = false, slideMode, }) {
3956
+ slideModeType.current = slideMode;
3957
+ if (typeof nextActiveItem === 'number') {
3958
+ if (!freeScroll) {
3959
+ activeItem.current = nextActiveItem;
3960
+ }
3961
+ emitEvent({
3962
+ eventName: 'onSlideStartChange',
3963
+ slideActionType: slideActionType.current,
3964
+ slideMode: slideModeType.current,
3965
+ nextItem: {
3966
+ startReached: firstItemReached.current,
3967
+ endReached: lastItemReached.current,
3968
+ index: freeScroll ? -1 : activeItem.current,
3969
+ id: freeScroll ? '' : items[activeItem.current].id,
3970
+ },
3971
+ });
3972
+ }
3973
+ prevSlidedValue.current = to;
3974
+ setSpring.start({
3975
+ immediate,
3976
+ from: {
3977
+ val: from,
3978
+ },
3979
+ to: {
3980
+ val: to,
3981
+ },
3982
+ config: Object.assign(Object.assign({}, config.default), { velocity: spring.val.velocity }),
3983
+ onRest(value) {
3984
+ if (!immediate && value.finished) {
3985
+ emitEvent({
3986
+ eventName: 'onSlideChange',
3987
+ slideActionType: slideActionType.current,
3988
+ slideMode: slideModeType.current,
3989
+ currentItem: {
3990
+ startReached: firstItemReached.current,
3991
+ endReached: lastItemReached.current,
3992
+ index: freeScroll ? -1 : activeItem.current,
3993
+ id: freeScroll ? '' : items[activeItem.current].id,
3994
+ },
3995
+ });
3996
+ }
3997
+ },
3998
+ });
3999
+ if (withThumbs && !immediate) {
4000
+ handleScroll(activeItem.current);
4001
+ }
4002
+ }
4003
+ function getTotalScrollValue() {
4004
+ var _a;
4005
+ if (withLoop) {
4006
+ return getSlideValue() * items.length;
4007
+ }
4008
+ return Math.round(Number((_a = carouselTrackWrapperRef.current) === null || _a === void 0 ? void 0 : _a[carouselSlideAxis === 'x' ? 'scrollWidth' : 'scrollHeight']) -
4009
+ carouselTrackWrapperRef.current.getBoundingClientRect()[carouselSlideAxis === 'x' ? 'width' : 'height']);
4010
+ }
4011
+ function getAnimatedWrapperStyles() {
4012
+ const percentValue = `calc(100% - ${startEndGutter * 2}px)`;
4013
+ return {
4014
+ width: carouselSlideAxis === 'x' ? percentValue : '100%',
4015
+ height: carouselSlideAxis === 'y' ? percentValue : '100%',
4016
+ };
4017
+ }
4018
+ function getCarouselItemWidth() {
4019
+ var _a;
4020
+ const carouselItem = (_a = carouselTrackWrapperRef.current) === null || _a === void 0 ? void 0 : _a.querySelector('.use-spring-carousel-item');
4021
+ if (!carouselItem) {
4022
+ throw Error('No carousel items available!');
4023
+ }
4024
+ return (carouselItem.getBoundingClientRect()[carouselSlideAxis === 'x' ? 'width' : 'height'] + gutter);
4025
+ }
4026
+ function adjustCarouselWrapperPosition() {
4027
+ const positionProperty = carouselSlideAxis === 'x' ? 'left' : 'top';
4028
+ function setPosition(v) {
4029
+ const ref = carouselTrackWrapperRef.current;
4030
+ if (!ref)
4031
+ return;
4032
+ if (withLoop) {
4033
+ ref.style.top = '0px';
4034
+ ref.style.left = '0px';
4035
+ ref.style[positionProperty] = `-${v - startEndGutter}px`;
4036
+ }
4037
+ else {
4038
+ ref.style.left = '0px';
4039
+ ref.style.top = '0px';
4040
+ }
4041
+ }
4042
+ const currentFromValue = Math.abs(getFromValue());
4043
+ if (currentFromValue < getTotalScrollValue() && lastItemReached.current) {
4044
+ lastItemReached.current = false;
4045
+ }
4046
+ if (currentFromValue > getTotalScrollValue()) {
4047
+ const val = -getTotalScrollValue();
4048
+ lastItemReached.current = true;
4049
+ prevSlidedValue.current = val;
4050
+ setSpring.start({
4051
+ immediate: true,
4052
+ val,
4053
+ });
4054
+ return;
4055
+ }
4056
+ if (initialStartingPosition === 'center') {
4057
+ setPosition(getCarouselItemWidth() * items.length -
4058
+ getSlideValue() * Math.round((itemsPerSlide - 1) / 2));
4059
+ }
4060
+ else if (initialStartingPosition === 'end') {
4061
+ setPosition(getCarouselItemWidth() * items.length -
4062
+ getSlideValue() * Math.round(itemsPerSlide - 1));
4063
+ }
4064
+ else {
4065
+ setPosition(getCarouselItemWidth() * items.length);
4066
+ }
4067
+ if (!freeScroll && slideType === 'fixed') {
4068
+ const val = -(getSlideValue() * activeItem.current);
4069
+ prevSlidedValue.current = val;
4070
+ setSpring.start({
4071
+ immediate: true,
4072
+ val,
4073
+ });
4074
+ }
4075
+ }
4076
+ function getFromValue() {
4077
+ if (freeScroll && mainCarouselWrapperRef.current) {
4078
+ return mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'];
4079
+ }
4080
+ return spring.val.get();
4081
+ }
4082
+ function getToValue(type, index) {
4083
+ if (freeScroll && type === 'next') {
4084
+ const next = prevSlidedValue.current + getSlideValue();
4085
+ if (next > getTotalScrollValue()) {
4086
+ return getTotalScrollValue();
4087
+ }
4088
+ return next;
4089
+ }
4090
+ if (freeScroll && type === 'prev') {
4091
+ const next = prevSlidedValue.current - getSlideValue();
4092
+ if (next < 0) {
4093
+ return 0;
4094
+ }
4095
+ return next;
4096
+ }
4097
+ if (type === 'next') {
4098
+ if (index) {
4099
+ return -(index * getSlideValue());
4100
+ }
4101
+ return prevSlidedValue.current - getSlideValue();
4102
+ }
4103
+ if (index) {
4104
+ return -(index * getSlideValue());
4105
+ }
4106
+ return prevSlidedValue.current + getSlideValue();
4107
+ }
4108
+ function slideToPrevItem(type = 'click', index) {
4109
+ if (!init || (firstItemReached.current && !withLoop))
4110
+ return;
4111
+ slideActionType.current = 'prev';
4112
+ lastItemReached.current = false;
4113
+ const nextItem = index || activeItem.current - 1;
4114
+ if (!withLoop) {
4115
+ const nextItemWillExceed = getToValue('prev', index) + getSlideValue() / 3 > 0;
4116
+ if (firstItemReached.current)
4117
+ return;
4118
+ if (nextItemWillExceed) {
4119
+ firstItemReached.current = true;
4120
+ lastItemReached.current = false;
4121
+ slideToItem({
4122
+ slideMode: type,
4123
+ from: getFromValue(),
4124
+ to: 0,
4125
+ nextActiveItem: 0,
4126
+ });
4127
+ return;
4128
+ }
4129
+ }
4130
+ if (withLoop && firstItemReached.current) {
4131
+ firstItemReached.current = false;
4132
+ lastItemReached.current = true;
4133
+ slideToItem({
4134
+ slideMode: type,
4135
+ from: getFromValue() - getSlideValue() * items.length,
4136
+ to: -(getSlideValue() * items.length) + getSlideValue(),
4137
+ nextActiveItem: items.length - 1,
4138
+ });
4139
+ return;
4140
+ }
4141
+ if (nextItem === 0) {
4142
+ firstItemReached.current = true;
4143
+ }
4144
+ if (nextItem === items.length - 1 || nextItem === -1) {
4145
+ lastItemReached.current = true;
4146
+ }
4147
+ slideToItem({
4148
+ slideMode: type,
4149
+ from: getFromValue(),
4150
+ to: getToValue('prev', index),
4151
+ nextActiveItem: nextItem,
4152
+ });
4153
+ }
4154
+ function slideToNextItem(type = 'click', index) {
4155
+ if (!init || (lastItemReached.current && !withLoop))
4156
+ return;
4157
+ slideActionType.current = 'next';
4158
+ firstItemReached.current = false;
4159
+ const nextItem = index || activeItem.current + 1;
4160
+ if (!withLoop) {
4161
+ const nextItemWillExceed = Math.abs(getToValue('next', index)) > getTotalScrollValue() - getSlideValue() / 3;
4162
+ if (lastItemReached.current)
4163
+ return;
4164
+ if (nextItemWillExceed) {
4165
+ firstItemReached.current = false;
4166
+ lastItemReached.current = true;
4167
+ slideToItem({
4168
+ slideMode: type,
4169
+ from: getFromValue(),
4170
+ to: -getTotalScrollValue(),
4171
+ nextActiveItem: nextItem,
4172
+ });
4173
+ return;
4174
+ }
4175
+ }
4176
+ if (withLoop && lastItemReached.current) {
4177
+ lastItemReached.current = false;
4178
+ firstItemReached.current = true;
4179
+ slideToItem({
4180
+ slideMode: type,
4181
+ from: getFromValue() + getSlideValue() * items.length,
4182
+ to: 0,
4183
+ nextActiveItem: 0,
4184
+ });
4185
+ return;
4186
+ }
4187
+ if (nextItem === 0) {
4188
+ firstItemReached.current = true;
4189
+ }
4190
+ if (nextItem === items.length - 1) {
4191
+ lastItemReached.current = true;
4192
+ }
4193
+ slideToItem({
4194
+ slideMode: type,
4195
+ from: getFromValue(),
4196
+ to: getToValue('next', index),
4197
+ nextActiveItem: nextItem,
4198
+ });
4199
+ }
4200
+ React.useEffect(() => {
4201
+ prevWindowWidth.current = window.innerWidth;
4202
+ }, []);
4203
+ React.useEffect(() => {
4204
+ adjustCarouselWrapperPosition();
4205
+ }, [
4206
+ initialStartingPosition,
4207
+ itemsPerSlide,
4208
+ withLoop,
4209
+ startEndGutter,
4210
+ gutter,
4211
+ freeScroll,
4212
+ slideType,
4213
+ init,
4214
+ ]);
4215
+ React.useLayoutEffect(() => {
4216
+ /**
4217
+ * Set initial track position
4218
+ */
4219
+ if (carouselTrackWrapperRef.current) {
4220
+ adjustCarouselWrapperPosition();
4221
+ }
4222
+ }, []);
4223
+ React.useEffect(() => {
4224
+ if (_draggingSlideTreshold) {
4225
+ draggingSlideTreshold.current = _draggingSlideTreshold;
4226
+ }
4227
+ else {
4228
+ draggingSlideTreshold.current = Math.floor(getSlideValue() / 2 / 2);
4229
+ }
4230
+ }, [_draggingSlideTreshold]);
4231
+ React.useEffect(() => {
4232
+ function handleResize() {
4233
+ if (window.innerWidth === prevWindowWidth.current)
4234
+ return;
4235
+ prevWindowWidth.current = window.innerWidth;
4236
+ adjustCarouselWrapperPosition();
4237
+ }
4238
+ window.addEventListener('resize', handleResize);
4239
+ return () => {
4240
+ window.removeEventListener('resize', handleResize);
4241
+ };
4242
+ }, []);
4243
+ const bindDrag = react.useDrag(state => {
4244
+ const isDragging = state.dragging;
4245
+ const movement = state.offset[carouselSlideAxis === 'x' ? 0 : 1];
4246
+ const currentMovement = state.movement[carouselSlideAxis === 'x' ? 0 : 1];
4247
+ const direction = state.direction[carouselSlideAxis === 'x' ? 0 : 1];
4248
+ const prevItemTreshold = currentMovement > draggingSlideTreshold.current;
4249
+ const nextItemTreshold = currentMovement < -draggingSlideTreshold.current;
4250
+ if (isDragging) {
4251
+ if (direction > 0) {
4252
+ slideActionType.current = 'prev';
4253
+ }
4254
+ else {
4255
+ slideActionType.current = 'next';
4256
+ }
4257
+ emitEvent(Object.assign(Object.assign({}, state), { eventName: 'onDrag', slideActionType: slideActionType.current }));
4258
+ if (freeScroll) {
4259
+ if (slideActionType.current === 'prev' && movement > 0) {
4260
+ state.cancel();
4261
+ setSpring.start({
4262
+ from: {
4263
+ val: getFromValue(),
4264
+ },
4265
+ to: {
4266
+ val: 0,
4267
+ },
4268
+ config: {
4269
+ velocity: state.velocity,
4270
+ friction: 50,
4271
+ tension: 1000,
4272
+ },
4273
+ });
4274
+ return;
4275
+ }
4276
+ setSpring.start({
4277
+ from: {
4278
+ val: getFromValue(),
4279
+ },
4280
+ to: {
4281
+ val: -movement,
4282
+ },
4283
+ config: {
4284
+ velocity: state.velocity,
4285
+ friction: 50,
4286
+ tension: 1000,
4287
+ },
4288
+ });
4289
+ return;
4290
+ }
4291
+ setSpring.start({
4292
+ val: movement,
4293
+ config: {
4294
+ velocity: state.velocity,
4295
+ friction: 50,
4296
+ tension: 1000,
4297
+ },
4298
+ });
4299
+ if (slideWhenThresholdIsReached && nextItemTreshold) {
4300
+ slideToNextItem('drag');
4301
+ state.cancel();
4302
+ }
4303
+ else if (slideWhenThresholdIsReached && prevItemTreshold) {
4304
+ slideToPrevItem('drag');
4305
+ state.cancel();
4306
+ }
4307
+ return;
4308
+ }
4309
+ if (state.last && !state.canceled && freeScroll) {
4310
+ if (slideActionType.current === 'prev') {
4311
+ slideToPrevItem('drag');
4312
+ }
4313
+ if (slideActionType.current === 'next') {
4314
+ slideToNextItem('drag');
4315
+ }
4316
+ }
4317
+ if (state.last && !state.canceled && !freeScroll) {
4318
+ if (nextItemTreshold) {
4319
+ if (!withLoop && lastItemReached.current) {
4320
+ setSpring.start({
4321
+ val: -getTotalScrollValue(),
4322
+ config: Object.assign(Object.assign({}, config.default), { velocity: state.velocity }),
4323
+ });
4324
+ }
4325
+ else {
4326
+ slideToNextItem('drag');
4327
+ }
4328
+ }
4329
+ else if (prevItemTreshold) {
4330
+ if (!withLoop && firstItemReached.current) {
4331
+ setSpring.start({
4332
+ val: 0,
4333
+ config: Object.assign(Object.assign({}, config.default), { velocity: state.velocity }),
4334
+ });
4335
+ }
4336
+ else {
4337
+ slideToPrevItem('drag');
4338
+ }
4339
+ }
4340
+ else {
4341
+ setSpring.start({
4342
+ val: prevSlidedValue.current,
4343
+ config: Object.assign(Object.assign({}, config.default), { velocity: state.velocity }),
4344
+ });
4345
+ }
4346
+ }
4347
+ }, {
4348
+ enabled: (init && !disableGestures && !freeScroll) ||
4349
+ (!!freeScroll && !!enableFreeScrollDrag),
4350
+ axis: carouselSlideAxis,
4351
+ from: () => {
4352
+ if (freeScroll && mainCarouselWrapperRef.current) {
4353
+ return [
4354
+ -mainCarouselWrapperRef.current.scrollLeft,
4355
+ -mainCarouselWrapperRef.current.scrollTop,
4356
+ ];
4357
+ }
4358
+ if (carouselSlideAxis === 'x') {
4359
+ return [spring.val.get(), spring.val.get()];
4360
+ }
4361
+ return [spring.val.get(), spring.val.get()];
4362
+ },
4363
+ });
4364
+ function getWrapperOverflowStyles() {
4365
+ if (freeScroll) {
4366
+ if (carouselSlideAxis === 'x') {
4367
+ return {
4368
+ overflowX: 'auto',
4369
+ };
4370
+ }
4371
+ return {
4372
+ overflowY: 'auto',
4373
+ };
4374
+ }
4375
+ return {};
4376
+ }
4377
+ function setStartEndItemReachedOnFreeScroll() {
4378
+ if (mainCarouselWrapperRef.current) {
4379
+ prevSlidedValue.current =
4380
+ mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'];
4381
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'] === 0) {
4382
+ firstItemReached.current = true;
4383
+ lastItemReached.current = false;
4384
+ }
4385
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'] > 0 &&
4386
+ mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'] < getTotalScrollValue()) {
4387
+ firstItemReached.current = false;
4388
+ lastItemReached.current = false;
4389
+ }
4390
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'] === getTotalScrollValue()) {
4391
+ firstItemReached.current = false;
4392
+ lastItemReached.current = true;
4393
+ }
4394
+ }
4395
+ }
4396
+ function getScrollHandlers() {
4397
+ if (freeScroll) {
4398
+ return {
4399
+ onWheel() {
4400
+ spring.val.stop();
4401
+ setStartEndItemReachedOnFreeScroll();
4402
+ },
4403
+ };
4404
+ }
4405
+ return {};
4406
+ }
4407
+ function findItemIndex(id) {
4408
+ return items.findIndex(item => item.id === id);
4409
+ }
4410
+ function findItemIndexById(id, error) {
4411
+ let itemIndex = 0;
4412
+ if (typeof id === 'string') {
4413
+ itemIndex = items.findIndex(_item => _item.id === id);
4414
+ }
4415
+ else {
4416
+ itemIndex = id;
4417
+ }
4418
+ if (itemIndex < 0 || itemIndex >= items.length) {
4419
+ throw new Error(error);
4420
+ }
4421
+ return itemIndex;
4422
+ }
4423
+ function internalSlideToItem(id) {
4424
+ if (!init)
4425
+ return;
4426
+ firstItemReached.current = false;
4427
+ lastItemReached.current = false;
4428
+ const itemIndex = findItemIndexById(id, "The item you want to slide to doesn't exist; please check che item id or the index you're passing to.");
4429
+ if (itemIndex === activeItem.current) {
4430
+ return;
4431
+ }
4432
+ const currentItem = findItemIndex(items[activeItem.current].id);
4433
+ const newActiveItem = findItemIndex(items[itemIndex].id);
4434
+ if (newActiveItem > currentItem) {
4435
+ slideToNextItem('click', newActiveItem);
4436
+ }
4437
+ else {
4438
+ slideToPrevItem('click', newActiveItem);
4439
+ }
4440
+ }
4441
+ function getIsNextItem(id) {
4442
+ const itemIndex = findItemIndex(id);
4443
+ const _activeItem = activeItem.current;
4444
+ if (withLoop && _activeItem === items.length - 1) {
4445
+ return itemIndex === 0;
4446
+ }
4447
+ return itemIndex === _activeItem + 1;
4448
+ }
4449
+ function getIsPrevItem(id) {
4450
+ const itemIndex = findItemIndex(id);
4451
+ const _activeItem = activeItem.current;
4452
+ if (withLoop && _activeItem === 0) {
4453
+ return itemIndex === items.length - 1;
4454
+ }
4455
+ return itemIndex === _activeItem - 1;
4456
+ }
4457
+ const carouselFragment = (jsxRuntime.jsx("div", Object.assign({ ref: mainCarouselWrapperRef }, getScrollHandlers(), { style: Object.assign({ display: 'flex', position: 'relative', width: '100%', height: '100%' }, getWrapperOverflowStyles()) }, { children: jsxRuntime.jsx("div", Object.assign({ ref: carouselTrackWrapperRef }, bindDrag(), { style: Object.assign({ position: 'relative', display: 'flex', flexDirection: carouselSlideAxis === 'x' ? 'row' : 'column', touchAction: 'none' }, getAnimatedWrapperStyles()) }, { children: internalItems.map((item, index) => {
4458
+ return (jsxRuntime.jsx("div", Object.assign({ className: "use-spring-carousel-item", "data-testid": "use-spring-carousel-item-wrapper", style: Object.assign({ display: 'flex', position: 'relative', flex: '1' }, getItemStyles()) }, { children: item.renderItem }), `${item.id}-${index}`));
4459
+ }) })) })));
4460
+ return {
4461
+ useListenToCustomEvent,
4462
+ carouselFragment,
4463
+ enterFullscreen,
4464
+ exitFullscreen,
4465
+ getIsFullscreen,
4466
+ thumbsFragment,
4467
+ slideToItem: internalSlideToItem,
4468
+ getIsNextItem,
4469
+ getIsPrevItem,
4470
+ slideToPrevItem: () => slideToPrevItem(),
4471
+ slideToNextItem: () => slideToNextItem(),
4472
+ getIsActiveItem: (id) => {
4473
+ return (findItemIndexById(id, "The item you want to check doesn't exist") ===
4474
+ activeItem.current);
4475
+ },
4476
+ };
4477
+ }
4478
+ const Context = React.createContext(undefined);
4479
+ function useSpringCarouselContext() {
4480
+ const context = React.useContext(Context);
4481
+ if (!context) {
4482
+ throw new Error('useSpringCarouselContext must be used within the carousel.');
4483
+ }
4484
+ return context;
4485
+ }
4486
+
4487
+ exports.useSpringCarousel = useSpringCarousel;
4488
+ exports.useSpringCarouselContext = useSpringCarouselContext;
4489
+
4490
+ }));
2
4491
  //# sourceMappingURL=index.js.map