forked from google-fabric/velocity-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvelocity-transition-group.js
501 lines (414 loc) · 19.1 KB
/
velocity-transition-group.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
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/*
Copyright (c) 2015 Twitter, Inc. and other contributors
Component to add Velocity animations around React transitions. Delegates to the React TransitionGroup
addon.
Properties
enter: Animation to run on a child component being added
leave: Animation to run on a child component leaving
runOnMount: if true, runs the "enter" animation on the elements that exist as children when this
component is mounted.
enterHideStyle/enterShowStyle: see below.
Any additional properties (e.g. "className", "component") will be passed to the internal
TransitionGroup.
"enter" and "leave" should either be a string naming an animation, or a hash with an
"animation" key that can either be a string itself, or a hash of style attributes to animate (this
value is passed to Velocity its the first arg).
If "enter" or "leave" is a hash, it can additionally have a "style" value that is applied the tick
before the Velocity animation starts. Use this for non-animating properties (like "position") that
are prerequisites for correct animation. The style value is applied using Velocity's JS -> CSS
routines, which may differ from React's.
Any hash entries beyond "animation" and "style" are passed in an options hash to Velocity. Use this
for options like "stagger", "reverse", &tc.
By default, this component will immediately hide all entering children with display: 'none', and
unhide them one tick later with display: ''. This is done so that we can coalesce multiple enters
into a single animation, and we want to avoid any popping of elements in while they're collected. If
you prefer a different way of hiding these elements so that e.g. geometry can be immediately
calculated, use the enterHideStyle and enterShowStyle props to provide alternate style hashes for
hiding and revealing entering elements.
Statics
disabledForTest: Set this to true globally to turn off all custom animation logic. Instead, this
component will behave like a vanilla TransitionGroup.
Inspired by https://gist.github.com/tkafka/0d94c6ec94297bb67091
*/
/* eslint react/no-find-dom-node: 0 */
var _ = {
each: require('lodash/each'),
extend: require('lodash/extend'),
forEach: require('lodash/forEach'),
isEqual: require('lodash/isEqual'),
keys: require('lodash/keys'),
omit: require('lodash/omit'),
map: require('lodash/map')
};
var React = require('react');
var ReactDOM = require('react-dom');
var PropTypes = require('prop-types');
var TransitionGroup = require('react-transition-group/TransitionGroup');
var Transition = require('react-transition-group/Transition').default;
var Velocity = require('./lib/velocity-animate-shim');
// Shim requestAnimationFrame for browsers that don't support it, in particular IE 9.
var shimRequestAnimationFrame = typeof window !== 'undefined' && (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 0);
});
// Fix 'Invalid calling object' error in IE
shimRequestAnimationFrame = typeof window !== 'undefined' && shimRequestAnimationFrame.bind(window);
var shimCancelAnimationFrame = typeof window !== 'undefined' && (window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || function (timeout) {
window.clearTimeout(timeout);
});
shimCancelAnimationFrame = typeof window !== 'undefined' && shimCancelAnimationFrame.bind(window);
// Internal wrapper for the transitioned elements. Delegates all child lifecycle events to the
// parent VelocityTransitionGroup so that it can co-ordinate animating all of the elements at once.
var VelocityTransitionGroupChild = function (_React$Component) {
_inherits(VelocityTransitionGroupChild, _React$Component);
function VelocityTransitionGroupChild() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, VelocityTransitionGroupChild);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = VelocityTransitionGroupChild.__proto__ || Object.getPrototypeOf(VelocityTransitionGroupChild)).call.apply(_ref, [this].concat(args))), _this), _this.lastState = 'appear', _this.componentWillEnter = function (node, appearing) {
_this.lastState = appearing ? 'appear' : 'enter';
}, _this.componentWillExit = function () {
_this.lastState = 'exit';
}, _this.endListener = function (node, done) {
switch (_this.lastState) {
case 'appear':
_this.props.willAppearFunc(node, done);
break;
case 'enter':
_this.props.willEnterFunc(node, done);
break;
case 'exit':
_this.props.willLeaveFunc(node, done);
break;
}
}, _temp), _possibleConstructorReturn(_this, _ret);
}
// We trigger our transitions out of endListener because that gives us access to the done callback
// we can use to tell the Transition that the animation has completed.
_createClass(VelocityTransitionGroupChild, [{
key: 'componentWillUnmount',
value: function componentWillUnmount() {
// Clear references from velocity cache.
Velocity.Utilities.removeData(ReactDOM.findDOMNode(this), ['velocity', 'fxqueue']);
}
}, {
key: 'render',
value: function render() {
var transitionProps = _.omit(this.props, _.keys(VelocityTransitionGroupChild.propTypes));
return React.createElement(Transition, _extends({}, transitionProps, {
timeout: null,
addEndListener: this.endListener,
appear: true,
onEnter: this.componentWillEnter,
onExit: this.componentWillExit
}), this.props.children);
}
}]);
return VelocityTransitionGroupChild;
}(React.Component);
VelocityTransitionGroupChild.propTypes = {
children: PropTypes.element.isRequired,
willAppearFunc: PropTypes.func.isRequired,
willEnterFunc: PropTypes.func.isRequired,
willLeaveFunc: PropTypes.func.isRequired
};
var VelocityTransitionGroup = function (_React$Component2) {
_inherits(VelocityTransitionGroup, _React$Component2);
function VelocityTransitionGroup(props) {
_classCallCheck(this, VelocityTransitionGroup);
var _this2 = _possibleConstructorReturn(this, (VelocityTransitionGroup.__proto__ || Object.getPrototypeOf(VelocityTransitionGroup)).call(this, props));
_this2._scheduledAnimationFrame = null;
_this2._scheduledAnimationRunFrames = [];
_this2._entering = [];
_this2._leaving = [];
_this2._timers = [];
_this2._unmounted = false;
_this2.childWillAppear = _this2.childWillAppear.bind(_this2);
_this2.childWillEnter = _this2.childWillEnter.bind(_this2);
_this2.childWillLeave = _this2.childWillLeave.bind(_this2);
_this2._runAnimations = _this2._runAnimations.bind(_this2);
_this2._wrapChild = _this2._wrapChild.bind(_this2);
return _this2;
}
_createClass(VelocityTransitionGroup, [{
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (this._scheduledAnimationFrame) {
shimCancelAnimationFrame(this._scheduledAnimationFrame);
}
_.forEach(this._timers, function (timer) {
clearTimeout(timer);
});
_.forEach(this._scheduledAnimationRunFrames, function (frame) {
shimCancelAnimationFrame(frame);
});
// We don't cancel all the in-process animations, so we use this to know if the component
// is gone when an animation is over.
this._unmounted = true;
}
}, {
key: 'render',
value: function render() {
// Pass any props that are not our own on into the TransitionGroup delegate.
var transitionGroupProps = _.omit(this.props, _.keys(VelocityTransitionGroup.propTypes));
return React.createElement(TransitionGroup, transitionGroupProps, !this.constructor.disabledForTest && !Velocity.velocityReactServerShim ? React.Children.map(this.props.children, this._wrapChild) : this.props.children);
}
}, {
key: 'childWillAppear',
value: function childWillAppear(node, doneFn) {
var _this3 = this;
if (this.props.runOnMount) {
this.childWillEnter(node, doneFn);
} else {
this._finishAnimation(node, this.props.enter);
// Important to tick over so that any callbacks due to finishing the animation complete first.
//
// Using setTimeout so that doneFn gets called even when the tab is hidden.
var t = setTimeout(function () {
var idx = _this3._timers.indexOf(t);
if (idx >= 0) {
_this3._timers.splice(idx, 1);
}
doneFn();
}, 0);
this._timers.push(t);
}
}
}, {
key: 'childWillEnter',
value: function childWillEnter(node, doneFn) {
if (this._shortCircuitAnimation(this.props.enter, doneFn)) return;
// By finishing a "leave" on the element, we put it in the right state to be animated in. Useful
// if "leave" includes a rotation or something that we'd like to have as our starting point, for
// symmetry.
// We use overrideOpts to prevent any "begin" or "complete" callback from triggering in this case, since
// it doesn't make a ton of sense.
this._finishAnimation(node, this.props.leave, {
begin: undefined,
complete: undefined
});
// We're not going to start the animation for a tick, so set the node's display to none (or any
// custom "hide" style provided) so that it doesn't flash in.
_.forEach(this.props.enterHideStyle, function (val, key) {
Velocity.CSS.setPropertyValue(node, key, val);
});
this._entering.push({
node: node,
doneFn: doneFn
});
this._schedule();
}
}, {
key: 'childWillLeave',
value: function childWillLeave(node, doneFn) {
if (this._shortCircuitAnimation(this.props.leave, doneFn)) return;
this._leaving.push({
node: node,
doneFn: doneFn
});
this._schedule();
}
// document.hidden check is there because animation completion callbacks won't fire (due to
// chaining off of rAF), which would prevent entering / leaving DOM nodes from being cleaned up
// while the tab is hidden.
//
// Returns true if this did short circuit, false if lifecycle methods should continue with
// their animations.
}, {
key: '_shortCircuitAnimation',
value: function _shortCircuitAnimation(animationProp, doneFn) {
if (document.hidden || this._parseAnimationProp(animationProp).animation == null) {
doneFn();
return true;
} else {
return false;
}
}
}, {
key: '_schedule',
value: function _schedule() {
if (this._scheduledAnimationFrame) {
return;
}
// Need rAF to make sure we're in the same event queue as Velocity from here out. Important
// for avoiding getting wrong interleaving with Velocity callbacks.
this._scheduledAnimationFrame = shimRequestAnimationFrame(this._runAnimations);
}
// arrow function because this is used as an rAF callback
}, {
key: '_runAnimations',
value: function _runAnimations() {
this._scheduledAnimationFrame = null;
this._runAnimation(true, this._entering, this.props.enter);
this._runAnimation(false, this._leaving, this.props.leave);
this._entering = [];
this._leaving = [];
}
// Used to parse out the 'enter' and 'leave' properties. Handles cases where they are omitted
// as well as when they are just strings and not hashes of animation and options.
}, {
key: '_parseAnimationProp',
value: function _parseAnimationProp(animationProp) {
var animation, opts, style;
if (typeof animationProp === 'string') {
animation = animationProp;
style = null;
opts = {};
} else {
animation = animationProp != null ? animationProp.animation : null;
style = animationProp != null ? animationProp.style : null;
opts = _.omit(animationProp, 'animation', 'style');
}
return {
animation: animation,
style: style,
opts: opts
};
}
}, {
key: '_runAnimation',
value: function _runAnimation(entering, queue, animationProp) {
var _this4 = this;
if (queue.length === 0) {
return;
}
var nodes = _.map(queue, 'node');
var doneFns = _.map(queue, 'doneFn');
var parsedAnimation = this._parseAnimationProp(animationProp);
var animation = parsedAnimation.animation;
var style = parsedAnimation.style;
var opts = parsedAnimation.opts;
// Clearing display reverses the behavior from childWillAppear where all elements are added with
// display: none to prevent them from flashing in before the animation starts. We don't do this
// for the fade/slide animations or any animation that ends in "In," since Velocity will handle
// it for us.
//
// If a custom "enterShowStyle" prop is passed, (i.e. not one that just reverses display: none)
// we always run it, regardless of the animation, since it's probably doing something around
// opacity or positioning that Velocity will not necessarily reset.
if (entering) {
if (!_.isEqual(this.props.enterShowStyle, { display: '' }) || !(/^(fade|slide)/.test(animation) || /In$/.test(animation))) {
style = _.extend({}, this.props.enterShowStyle, style);
}
}
// Because Safari can synchronously repaint when CSS "display" is reset, we set styles for all
// browsers before the rAF tick below that starts the animation. This way you know in all
// cases that you need to support your static styles being visible on the element before
// the animation begins.
if (style != null) {
_.each(style, function (value, key) {
Velocity.hook(nodes, key, value);
});
}
var doneFn = function doneFn() {
// calling doneFns after the parent has unmounted leads to errors
if (_this4._unmounted) {
return;
}
doneFns.map(function (doneFn) {
doneFn();
});
};
// For nodes that are entering, we tell the TransitionGroup that we're done with them
// immediately. That way, they can be removed later before their entering animations complete.
// If we're leaving, we stop current animations (which may be partially-completed enter
// animations) so that we can then animate out. Velocity typically makes these transitions
// very smooth, correctly animating from whatever state the element is currently in.
if (entering) {
doneFn();
doneFn = null;
} else {
Velocity(nodes, 'stop');
}
var combinedCompleteFn;
if (doneFn && opts.complete) {
var optsCompleteFn = opts.complete;
combinedCompleteFn = function combinedCompleteFn() {
doneFn();
// preserve this / args from Velocity so the complete function has context for what completed
optsCompleteFn.apply(this, arguments);
};
} else {
// One or the other or neither.
combinedCompleteFn = doneFn || opts.complete;
}
// Bit of a hack. Without this rAF, sometimes an enter animation doesn't start running, or is
// stopped before getting anywhere. This should get us on the other side of both completeFn and
// any _finishAnimation that's happening.
var t = shimRequestAnimationFrame(function () {
var idx = _this4._scheduledAnimationRunFrames.indexOf(t);
if (idx >= 0) {
_this4._scheduledAnimationRunFrames.splice(idx, 1);
}
Velocity(nodes, animation, _.extend({}, opts, {
complete: combinedCompleteFn
}));
});
this._scheduledAnimationRunFrames.push(t);
}
}, {
key: '_finishAnimation',
value: function _finishAnimation(node, animationProp, overrideOpts) {
var parsedAnimation = this._parseAnimationProp(animationProp);
var animation = parsedAnimation.animation;
var style = parsedAnimation.style;
var opts = _.extend({}, parsedAnimation.opts, overrideOpts);
if (style != null) {
_.each(style, function (value, key) {
Velocity.hook(node, key, value);
});
}
if (animation != null) {
// Opts are relevant even though we're immediately finishing, since things like "display"
// can affect the animation outcome.
Velocity(node, animation, opts);
Velocity(node, 'finishAll', true);
}
}
}, {
key: '_wrapChild',
value: function _wrapChild(child) {
// Need to guard against falsey children, which React will sometimes pass
// in.
if (!child) {
return null;
}
return React.createElement(VelocityTransitionGroupChild, {
key: child.key,
willAppearFunc: this.childWillAppear,
willEnterFunc: this.childWillEnter,
willLeaveFunc: this.childWillLeave
}, child);
}
}]);
return VelocityTransitionGroup;
}(React.Component);
VelocityTransitionGroup.disabledForTest = false; // global, mutable, for disabling animations during test
VelocityTransitionGroup.propTypes = {
runOnMount: PropTypes.bool,
enter: PropTypes.any,
leave: PropTypes.any,
children: PropTypes.any,
enterHideStyle: PropTypes.object,
enterShowStyle: PropTypes.object
};
VelocityTransitionGroup.defaultProps = {
runOnMount: false,
enter: null,
leave: null,
enterHideStyle: {
display: 'none'
},
enterShowStyle: {
display: ''
}
};
module.exports = VelocityTransitionGroup;