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