File size: 6,259 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import {
  is,
  raf,
  flush,
  eachProp,
  Timeout,
  Globals as G,
} from '@react-spring/shared'
import { Falsy } from '@react-spring/types'

import { getDefaultProps } from './helpers'
import { AnimationTarget, InferState, InferProps } from './types/internal'
import { AnimationResult, AsyncResult, SpringChain, SpringToFn } from './types'
import { getCancelledResult, getFinishedResult } from './AnimationResult'

type AsyncTo<T> = SpringChain<T> | SpringToFn<T>

/** @internal */
export type RunAsyncProps<T extends AnimationTarget = any> = InferProps<T> & {
  callId: number
  parentId?: number
  cancel: boolean
  to?: any
}

/** @internal */
export interface RunAsyncState<T extends AnimationTarget = any> {
  paused: boolean
  pauseQueue: Set<() => void>
  resumeQueue: Set<() => void>
  timeouts: Set<Timeout>
  delayed?: boolean
  asyncId?: number
  asyncTo?: AsyncTo<InferState<T>>
  promise?: AsyncResult<T>
  cancelId?: number
}

/**
 * Start an async chain or an async script.
 *
 * Always call `runAsync` in the action callback of a `scheduleProps` call.
 *
 * The `T` parameter can be a set of animated values (as an object type)
 * or a primitive type for a single animated value.
 */
export function runAsync<T extends AnimationTarget>(
  to: AsyncTo<InferState<T>>,
  props: RunAsyncProps<T>,
  state: RunAsyncState<T>,
  target: T
): AsyncResult<T> {
  const { callId, parentId, onRest } = props
  const { asyncTo: prevTo, promise: prevPromise } = state

  if (!parentId && to === prevTo && !props.reset) {
    return prevPromise!
  }

  return (state.promise = (async () => {
    state.asyncId = callId
    state.asyncTo = to

    // The default props of any `animate` calls.
    const defaultProps = getDefaultProps<InferProps<T>>(props, (value, key) =>
      // The `onRest` prop is only called when the `runAsync` promise is resolved.
      key === 'onRest' ? undefined : value
    )

    let preventBail!: () => void
    let bail: (error: any) => void

    // This promise is rejected when the animation is interrupted.
    const bailPromise = new Promise<void>(
      (resolve, reject) => ((preventBail = resolve), (bail = reject))
    )

    const bailIfEnded = (bailSignal: BailSignal) => {
      const bailResult =
        // The `cancel` prop or `stop` method was used.
        (callId <= (state.cancelId || 0) && getCancelledResult(target)) ||
        // The async `to` prop was replaced.
        (callId !== state.asyncId && getFinishedResult(target, false))

      if (bailResult) {
        bailSignal.result = bailResult

        // Reject the `bailPromise` to ensure the `runAsync` promise
        // is not relying on the caller to rethrow the error for us.
        bail(bailSignal)
        throw bailSignal
      }
    }

    const animate: any = (arg1: any, arg2?: any) => {
      // Create the bail signal outside the returned promise,
      // so the generated stack trace is relevant.
      const bailSignal = new BailSignal()
      const skipAnimationSignal = new SkipAnimationSignal()

      return (async () => {
        if (G.skipAnimation) {
          /**
           * We need to stop animations if `skipAnimation`
           * is set in the Globals
           *
           */
          stopAsync(state)

          // create the rejection error that's handled gracefully
          skipAnimationSignal.result = getFinishedResult(target, false)
          bail(skipAnimationSignal)
          throw skipAnimationSignal
        }

        bailIfEnded(bailSignal)

        const props: any = is.obj(arg1) ? { ...arg1 } : { ...arg2, to: arg1 }
        props.parentId = callId

        eachProp(defaultProps, (value, key) => {
          if (is.und(props[key])) {
            props[key] = value
          }
        })

        const result = await target.start(props)
        bailIfEnded(bailSignal)

        if (state.paused) {
          await new Promise<void>(resume => {
            state.resumeQueue.add(resume)
          })
        }

        return result
      })()
    }

    let result!: AnimationResult<T>

    if (G.skipAnimation) {
      /**
       * We need to stop animations if `skipAnimation`
       * is set in the Globals
       */
      stopAsync(state)
      return getFinishedResult(target, false)
    }

    try {
      let animating!: Promise<void>

      // Async sequence
      if (is.arr(to)) {
        animating = (async (queue: any[]) => {
          for (const props of queue) {
            await animate(props)
          }
        })(to)
      }

      // Async script
      else {
        animating = Promise.resolve(to(animate, target.stop.bind(target)))
      }

      await Promise.all([animating.then(preventBail), bailPromise])
      result = getFinishedResult(target.get(), true, false)

      // Bail handling
    } catch (err) {
      if (err instanceof BailSignal) {
        result = err.result
      } else if (err instanceof SkipAnimationSignal) {
        result = err.result
      } else {
        throw err
      }

      // Reset the async state.
    } finally {
      if (callId == state.asyncId) {
        state.asyncId = parentId
        state.asyncTo = parentId ? prevTo : undefined
        state.promise = parentId ? prevPromise : undefined
      }
    }

    if (is.fun(onRest)) {
      raf.batchedUpdates(() => {
        onRest(result, target, target.item)
      })
    }

    return result
  })())
}

/** Stop the current `runAsync` call with `finished: false` (or with `cancelled: true` when `cancelId` is defined) */
export function stopAsync(state: RunAsyncState, cancelId?: number | Falsy) {
  flush(state.timeouts, t => t.cancel())
  state.pauseQueue.clear()
  state.resumeQueue.clear()
  state.asyncId = state.asyncTo = state.promise = undefined
  if (cancelId) state.cancelId = cancelId
}

/** This error is thrown to signal an interrupted async animation. */
export class BailSignal extends Error {
  result!: AnimationResult
  constructor() {
    super(
      'An async animation has been interrupted. You see this error because you ' +
        'forgot to use `await` or `.catch(...)` on its returned promise.'
    )
  }
}

export class SkipAnimationSignal extends Error {
  result!: AnimationResult

  constructor() {
    super('SkipAnimationSignal')
  }
}