-
-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathtweenable.js
542 lines (462 loc) · 14.1 KB
/
tweenable.js
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
import * as easingFunctions from './easing-functions';
// CONSTANTS
const DEFAULT_EASING = 'linear';
const DEFAULT_DURATION = 500;
const UPDATE_TIME = 1000 / 60;
const root = typeof window !== 'undefined' ? window : global;
const AFTER_TWEEN = 'afterTween';
const AFTER_TWEEN_END = 'afterTweenEnd';
const BEFORE_TWEEN = 'beforeTween';
const TWEEN_CREATED = 'tweenCreated';
const TYPE_FUNCTION = 'function';
const TYPE_STRING = 'string';
// requestAnimationFrame() shim by Paul Irish (modified for Shifty)
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
let scheduleFunction =
root.requestAnimationFrame ||
root.webkitRequestAnimationFrame ||
root.oRequestAnimationFrame ||
root.msRequestAnimationFrame ||
(root.mozCancelRequestAnimationFrame && root.mozRequestAnimationFrame) ||
setTimeout;
const noop = () => {};
let listHead = null;
let listTail = null;
const formulas = { ...easingFunctions };
/**
* Calculates the interpolated tween values of an Object for a given
* timestamp.
* @param {number} forPosition The position to compute the state for.
* @param {Object} currentState Current state properties.
* @param {Object} originalState: The original state properties the Object is
* tweening from.
* @param {Object} targetState: The destination state properties the Object
* is tweening to.
* @param {number} duration: The length of the tween in milliseconds.
* @param {number} timestamp: The UNIX epoch time at which the tween began.
* @param {Object<string|Function>} easing: This Object's keys must correspond
* to the keys in targetState.
* @returns {Object}
* @private
*/
export const tweenProps = (
forPosition,
currentState,
originalState,
targetState,
duration,
timestamp,
easing
) => {
const normalizedPosition =
forPosition < timestamp ? 0 : (forPosition - timestamp) / duration;
for (const key in currentState) {
const easingObjectProp = easing[key];
const easingFn = easingObjectProp.call
? easingObjectProp
: formulas[easingObjectProp];
const start = originalState[key];
currentState[key] =
start + (targetState[key] - start) * easingFn(normalizedPosition);
}
return currentState;
};
const processTween = (tween, currentTime) => {
const { _attachment, _currentState, _delay, _easing, _originalState } = tween;
let { _duration, _step, _targetState, _timestamp } = tween;
const endTime = _timestamp + _delay + _duration;
let timeToCompute = currentTime > endTime ? endTime : currentTime;
const hasEnded = timeToCompute >= endTime;
const offset = _duration - (endTime - timeToCompute);
if (hasEnded) {
_step(_targetState, _attachment, offset);
tween.stop(true);
} else {
tween._applyFilter(BEFORE_TWEEN);
// If the animation has not yet reached the start point (e.g., there was
// delay that has not yet completed), just interpolate the starting
// position of the tween.
if (timeToCompute < _timestamp + _delay) {
timeToCompute = 1;
_duration = 1;
_timestamp = 1;
} else {
_timestamp += _delay;
}
tweenProps(
timeToCompute,
_currentState,
_originalState,
_targetState,
_duration,
_timestamp,
_easing
);
tween._applyFilter(AFTER_TWEEN);
_step(_currentState, _attachment, offset);
}
};
export const processTweens = () => {
const currentTime = Tweenable.now();
let tween = listHead;
while (tween) {
processTween(tween, currentTime);
tween = tween._next;
}
};
/**
* Handles the update logic for one step of a tween.
* @param {number} [currentTimeOverride] Needed for accurate timestamp in
* shifty.Tweenable#seek.
* @private
*/
export const scheduleUpdate = () => {
if (!listHead) {
return;
}
scheduleFunction.call(root, scheduleUpdate, UPDATE_TIME);
processTweens();
};
/**
* Creates a usable easing Object from a string, a function or another easing
* Object. If `easing` is an Object, then this function clones it and fills
* in the missing properties with `"linear"`.
* @param {Object.<string|Function>} fromTweenParams
* @param {Object|string|Function} easing
* @return {Object.<string|Function>}
* @private
*/
export const composeEasingObject = (
fromTweenParams,
easing = DEFAULT_EASING
) => {
const composedEasing = {};
let typeofEasing = typeof easing;
if (typeofEasing === TYPE_STRING || typeofEasing === TYPE_FUNCTION) {
for (const prop in fromTweenParams) {
composedEasing[prop] = easing;
}
} else {
for (const prop in fromTweenParams) {
composedEasing[prop] = easing[prop] || DEFAULT_EASING;
}
}
return composedEasing;
};
const remove = tween => {
// Adapted from:
// https://github.com/trekhleb/javascript-algorithms/blob/7c9601df3e8ca4206d419ce50b88bd13ff39deb6/src/data-structures/doubly-linked-list/DoublyLinkedList.js#L73-L121
if (!listHead) {
return;
}
if (tween === listHead) {
listHead = tween._next;
if (listHead) {
listHead._previous = null;
}
if (tween === listTail) {
listTail = null;
}
} else if (tween === listTail) {
listTail = tween._previous;
listTail._next = null;
} else {
const previousTween = tween._previous;
const nextTween = tween._next;
previousTween._next = nextTween;
nextTween._previous = previousTween;
}
};
export class Tweenable {
/**
* @param {Object} [initialState={}] The values that the initial tween should
* start at if a `from` value is not provided to {@link
* shifty.Tweenable#tween} or {@link shifty.Tweenable#setConfig}.
* @param {shifty.tweenConfig} [config] Configuration object to be passed to
* {@link shifty.Tweenable#setConfig}.
* @constructs shifty.Tweenable
*/
constructor(initialState = {}, config = undefined) {
this._currentState = initialState;
this._configured = false;
this._filters = [];
this._next = null;
this._previous = null;
// To prevent unnecessary calls to setConfig do not set default
// configuration here. Only set default configuration immediately before
// tweening if none has been set.
if (config) {
this.setConfig(config);
}
}
/**
* Applies a filter to Tweenable instance.
* @param {string} filterName The name of the filter to apply.
* @private
*/
_applyFilter(filterName) {
for (const filterType of this._filters) {
const filter = filterType[filterName];
if (filter) {
filter(this);
}
}
}
/**
* Configure and start a tween.
* @method shifty.Tweenable#tween
* @param {shifty.tweenConfig} [config] Gets passed to {@link
* shifty.Tweenable#setConfig}.
* @return {external:Promise}
*/
tween(config = undefined) {
const { _attachment, _configured, _isTweening } = this;
if (_isTweening) {
return this;
}
// Only set default config if no configuration has been set previously and
// none is provided now.
if (config !== undefined || !_configured) {
this.setConfig(config);
}
this._timestamp = Tweenable.now();
this._start(this.get(), _attachment);
return this.resume();
}
/**
* Configure a tween that will start at some point in the future.
* @method shifty.Tweenable#setConfig
* @param {shifty.tweenConfig} [config={}]
* @return {shifty.Tweenable}
*/
setConfig({
attachment,
delay = 0,
duration = DEFAULT_DURATION,
easing,
from,
promise = Promise,
start = noop,
step = noop,
to,
}) {
this._configured = true;
// Attach something to this Tweenable instance (e.g.: a DOM element, an
// object, a string, etc.);
this._attachment = attachment;
// Init the internal state
this._pausedAtTime = null;
this._scheduleId = null;
this._delay = delay;
this._start = start;
this._step = step;
this._duration = duration;
this._currentState = { ...(from || this.get()) };
this._originalState = this.get();
this._targetState = { ...(to || this.get()) };
const { _currentState } = this;
// Ensure that there is always something to tween to.
this._targetState = { ..._currentState, ...this._targetState };
this._easing = composeEasingObject(_currentState, easing);
const { filters } = Tweenable;
this._filters.length = 0;
for (const name in filters) {
if (filters[name].doesApply(this)) {
this._filters.push(filters[name]);
}
}
this._applyFilter(TWEEN_CREATED);
this._promise = new promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
// Needed to silence (harmless) logged errors when a .catch handler is not
// added by downsteam code
this._promise.catch(noop);
return this;
}
/**
* @method shifty.Tweenable#get
* @return {Object} The current state.
*/
get() {
return { ...this._currentState };
}
/**
* Set the current state.
* @method shifty.Tweenable#set
* @param {Object} state The state to set.
*/
set(state) {
this._currentState = state;
}
/**
* Pause a tween. Paused tweens can be resumed from the point at which they
* were paused. This is different from {@link shifty.Tweenable#stop}, as
* that method causes a tween to start over when it is resumed.
* @method shifty.Tweenable#pause
* @return {shifty.Tweenable}
*/
pause() {
this._pausedAtTime = Tweenable.now();
this._isPaused = true;
remove(this);
return this;
}
/**
* Resume a paused tween.
* @method shifty.Tweenable#resume
* @return {external:Promise}
*/
resume() {
const currentTime = Tweenable.now();
if (this._isPaused) {
this._timestamp += currentTime - this._pausedAtTime;
}
this._isPaused = false;
this._isTweening = true;
if (listHead === null) {
listHead = this;
listTail = this;
scheduleUpdate();
} else {
this._previous = listTail;
this._previous._next = this;
listTail = this;
}
return this._promise;
}
/**
* Move the state of the animation to a specific point in the tween's
* timeline. If the animation is not running, this will cause {@link
* shifty.stepFunction} handlers to be called.
* @method shifty.Tweenable#seek
* @param {millisecond} millisecond The millisecond of the animation to seek
* to. This must not be less than `0`.
* @return {shifty.Tweenable}
*/
seek(millisecond) {
millisecond = Math.max(millisecond, 0);
const currentTime = Tweenable.now();
if (this._timestamp + millisecond === 0) {
return this;
}
this._timestamp = currentTime - millisecond;
if (!this.isPlaying()) {
this._isTweening = true;
this._isPaused = false;
// If the animation is not running, call scheduleUpdate to make sure that
// any step handlers are run.
processTween(this, currentTime);
this.pause();
}
return this;
}
/**
* Stops and cancels a tween.
* @param {boolean} [gotoEnd] If `false`, the tween just stops at its current
* state, and the tween promise is not resolved. If `true`, the tweened
* object's values are instantly set to the target values, and the promise is
* resolved.
* @method shifty.Tweenable#stop
* @return {shifty.Tweenable}
*/
stop(gotoEnd = false) {
const {
_attachment,
_currentState,
_easing,
_originalState,
_targetState,
} = this;
this._isTweening = false;
this._isPaused = false;
remove(this);
if (gotoEnd) {
this._applyFilter(BEFORE_TWEEN);
tweenProps(1, _currentState, _originalState, _targetState, 1, 0, _easing);
this._applyFilter(AFTER_TWEEN);
this._applyFilter(AFTER_TWEEN_END);
this._resolve(_currentState, _attachment);
} else {
this._reject(_currentState, _attachment);
}
return this;
}
/**
* Whether or not a tween is running.
* @method shifty.Tweenable#isPlaying
* @return {boolean}
*/
isPlaying() {
return this._isTweening && !this._isPaused;
}
/**
* @method shifty.Tweenable#setScheduleFunction
* @param {shifty.scheduleFunction} scheduleFunction
* @deprecated Will be removed in favor of {@link shifty.Tweenable.setScheduleFunction} in 3.0.
*/
setScheduleFunction(scheduleFunction) {
Tweenable.setScheduleFunction(scheduleFunction);
}
/**
* `delete` all "own" properties. Call this when the {@link
* shifty.Tweenable} instance is no longer needed to free memory.
* @method shifty.Tweenable#dispose
*/
dispose() {
for (const prop in this) {
delete this[prop];
}
}
}
/**
* Set a custom schedule function.
*
* By default,
* [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame)
* is used if available, otherwise
* [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout)
* is used.
* @method shifty.Tweenable.setScheduleFunction
* @param {shifty.scheduleFunction} fn The function to be
* used to schedule the next frame to be rendered.
* @return {shifty.scheduleFunction} The function that was set.
*/
Tweenable.setScheduleFunction = fn => (scheduleFunction = fn);
Tweenable.formulas = formulas;
/**
* The {@link shifty.filter}s available for use. These filters are
* automatically applied at tween-time by Shifty. You can define your own
* {@link shifty.filter}s and attach them to this object.
* @member shifty.Tweenable.filters
* @type {Object.<shifty.filter>}
*/
Tweenable.filters = {};
/**
* @method shifty.Tweenable.now
* @static
* @returns {number} The current timestamp.
*/
Tweenable.now = Date.now || (() => +new Date());
/**
* @method shifty.tween
* @param {shifty.tweenConfig} [config={}]
* @description Standalone convenience method that functions identically to
* {@link shifty.Tweenable#tween}. You can use this to create tweens without
* needing to set up a {@link shifty.Tweenable} instance.
*
* import { tween } from 'shifty';
*
* tween({ from: { x: 0 }, to: { x: 10 } }).then(
* () => console.log('All done!')
* );
*
* @returns {external:Promise}
*/
export function tween(config = {}) {
const tweenable = new Tweenable();
const promise = tweenable.tween(config);
promise.tweenable = tweenable;
return promise;
}