-
Notifications
You must be signed in to change notification settings - Fork 740
/
index.ts
411 lines (366 loc) · 10.8 KB
/
index.ts
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import { frameData } from "../frameloop/data"
import { FrameData } from "../frameloop/types"
import { sync } from "../frameloop"
import type { VisualElement } from "../render/VisualElement"
import { SubscriptionManager } from "../utils/subscription-manager"
import { velocityPerSecond } from "../utils/velocity-per-second"
export type Transformer<T> = (v: T) => T
/**
* @public
*/
export type Subscriber<T> = (v: T) => void
/**
* @public
*/
export type PassiveEffect<T> = (v: T, safeSetter: (v: T) => void) => void
export type StartAnimation = (complete: () => void) => () => void
export interface MotionValueEventCallbacks<V> {
animationStart: () => void
animationComplete: () => void
animationCancel: () => void
change: (latestValue: V) => void
renderRequest: () => void
velocityChange: (latestVelocity: number) => void
}
const isFloat = (value: any): value is string => {
return !isNaN(parseFloat(value))
}
export interface MotionValueOptions {
owner?: VisualElement
}
/**
* `MotionValue` is used to track the state and velocity of motion values.
*
* @public
*/
export class MotionValue<V = any> {
/**
* This will be replaced by the build step with the latest version number.
* When MotionValues are provided to motion components, warn if versions are mixed.
*/
version = "__VERSION__"
/**
* If a MotionValue has an owner, it was created internally within Framer Motion
* and therefore has no external listeners. It is therefore safe to animate via WAAPI.
*/
owner?: VisualElement
/**
* The current state of the `MotionValue`.
*
* @internal
*/
private current: V
/**
* The previous state of the `MotionValue`.
*
* @internal
*/
private prev: V
/**
* Duration, in milliseconds, since last updating frame.
*
* @internal
*/
private timeDelta: number = 0
/**
* Timestamp of the last time this `MotionValue` was updated.
*
* @internal
*/
private lastUpdated: number = 0
/**
* Add a passive effect to this `MotionValue`.
*
* A passive effect intercepts calls to `set`. For instance, `useSpring` adds
* a passive effect that attaches a `spring` to the latest
* set value. Hypothetically there could be a `useSmooth` that attaches an input smoothing effect.
*
* @internal
*/
private passiveEffect?: PassiveEffect<V>
/**
* A reference to the currently-controlling Popmotion animation
*
* @internal
*/
private stopAnimation?: null | (() => void)
/**
* Tracks whether this value can output a velocity. Currently this is only true
* if the value is numerical, but we might be able to widen the scope here and support
* other value types.
*
* @internal
*/
private canTrackVelocity = false
/**
* @param init - The initiating value
* @param config - Optional configuration options
*
* - `transformer`: A function to transform incoming values with.
*
* @internal
*/
constructor(init: V, options: MotionValueOptions = {}) {
this.prev = this.current = init
this.canTrackVelocity = isFloat(this.current)
this.owner = options.owner
}
/**
* Adds a function that will be notified when the `MotionValue` is updated.
*
* It returns a function that, when called, will cancel the subscription.
*
* When calling `onChange` inside a React component, it should be wrapped with the
* `useEffect` hook. As it returns an unsubscribe function, this should be returned
* from the `useEffect` function to ensure you don't add duplicate subscribers..
*
* ```jsx
* export const MyComponent = () => {
* const x = useMotionValue(0)
* const y = useMotionValue(0)
* const opacity = useMotionValue(1)
*
* useEffect(() => {
* function updateOpacity() {
* const maxXY = Math.max(x.get(), y.get())
* const newOpacity = transform(maxXY, [0, 100], [1, 0])
* opacity.set(newOpacity)
* }
*
* const unsubscribeX = x.on("change", updateOpacity)
* const unsubscribeY = y.on("change", updateOpacity)
*
* return () => {
* unsubscribeX()
* unsubscribeY()
* }
* }, [])
*
* return <motion.div style={{ x }} />
* }
* ```
*
* @privateRemarks
*
* We could look into a `useOnChange` hook if the above lifecycle management proves confusing.
*
* ```jsx
* useOnChange(x, () => {})
* ```
*
* @param subscriber - A function that receives the latest value.
* @returns A function that, when called, will cancel this subscription.
*
* @deprecated
*/
onChange(subscription: Subscriber<V>): () => void {
return this.on("change", subscription)
}
/**
* An object containing a SubscriptionManager for each active event.
*/
private events: {
[key: string]: SubscriptionManager<any>
} = {}
on<EventName extends keyof MotionValueEventCallbacks<V>>(
eventName: EventName,
callback: MotionValueEventCallbacks<V>[EventName]
) {
if (!this.events[eventName]) {
this.events[eventName] = new SubscriptionManager()
}
return this.events[eventName].add(callback)
}
clearListeners() {
for (const eventManagers in this.events) {
this.events[eventManagers].clear()
}
}
/**
* Attaches a passive effect to the `MotionValue`.
*
* @internal
*/
attach(passiveEffect: PassiveEffect<V>) {
this.passiveEffect = passiveEffect
}
/**
* Sets the state of the `MotionValue`.
*
* @remarks
*
* ```jsx
* const x = useMotionValue(0)
* x.set(10)
* ```
*
* @param latest - Latest value to set.
* @param render - Whether to notify render subscribers. Defaults to `true`
*
* @public
*/
set(v: V, render = true) {
if (!render || !this.passiveEffect) {
this.updateAndNotify(v, render)
} else {
this.passiveEffect(v, this.updateAndNotify)
}
}
setWithVelocity(prev: V, current: V, delta: number) {
this.set(current)
this.prev = prev
this.timeDelta = delta
}
updateAndNotify = (v: V, render = true) => {
this.prev = this.current
this.current = v
// Update timestamp
const { delta, timestamp } = frameData
if (this.lastUpdated !== timestamp) {
this.timeDelta = delta
this.lastUpdated = timestamp
sync.postRender(this.scheduleVelocityCheck)
}
// Update update subscribers
if (this.prev !== this.current && this.events.change) {
this.events.change.notify(this.current)
}
// Update velocity subscribers
if (this.events.velocityChange) {
this.events.velocityChange.notify(this.getVelocity())
}
// Update render subscribers
if (render && this.events.renderRequest) {
this.events.renderRequest.notify(this.current)
}
}
/**
* Returns the latest state of `MotionValue`
*
* @returns - The latest state of `MotionValue`
*
* @public
*/
get() {
return this.current
}
/**
* @public
*/
getPrevious() {
return this.prev
}
/**
* Returns the latest velocity of `MotionValue`
*
* @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.
*
* @public
*/
getVelocity() {
// This could be isFloat(this.prev) && isFloat(this.current), but that would be wasteful
return this.canTrackVelocity
? // These casts could be avoided if parseFloat would be typed better
velocityPerSecond(
parseFloat(this.current as any) -
parseFloat(this.prev as any),
this.timeDelta
)
: 0
}
/**
* Schedule a velocity check for the next frame.
*
* This is an instanced and bound function to prevent generating a new
* function once per frame.
*
* @internal
*/
private scheduleVelocityCheck = () => sync.postRender(this.velocityCheck)
/**
* Updates `prev` with `current` if the value hasn't been updated this frame.
* This ensures velocity calculations return `0`.
*
* This is an instanced and bound function to prevent generating a new
* function once per frame.
*
* @internal
*/
private velocityCheck = ({ timestamp }: FrameData) => {
if (timestamp !== this.lastUpdated) {
this.prev = this.current
if (this.events.velocityChange) {
this.events.velocityChange.notify(this.getVelocity())
}
}
}
hasAnimated = false
/**
* Registers a new animation to control this `MotionValue`. Only one
* animation can drive a `MotionValue` at one time.
*
* ```jsx
* value.start()
* ```
*
* @param animation - A function that starts the provided animation
*
* @internal
*/
start(animation: StartAnimation) {
this.stop()
return new Promise<void>((resolve) => {
this.hasAnimated = true
this.stopAnimation = animation(resolve)
if (this.events.animationStart) {
this.events.animationStart.notify()
}
}).then(() => {
if (this.events.animationComplete) {
this.events.animationComplete.notify()
}
this.clearAnimation()
})
}
/**
* Stop the currently active animation.
*
* @public
*/
stop() {
if (this.stopAnimation) {
this.stopAnimation()
if (this.events.animationCancel) {
this.events.animationCancel.notify()
}
}
this.clearAnimation()
}
/**
* Returns `true` if this value is currently animating.
*
* @public
*/
isAnimating() {
return !!this.stopAnimation
}
private clearAnimation() {
this.stopAnimation = null
}
/**
* Destroy and clean up subscribers to this `MotionValue`.
*
* The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
* handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
* created a `MotionValue` via the `motionValue` function.
*
* @public
*/
destroy() {
this.clearListeners()
this.stop()
}
}
export function motionValue<V>(init: V, options?: MotionValueOptions) {
return new MotionValue<V>(init, options)
}