Animate.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  2. var _excluded = ["children", "begin", "duration", "attributeName", "easing", "isActive", "steps", "from", "to", "canBegin", "onAnimationEnd", "shouldReAnimate", "onAnimationReStart"];
  3. function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
  4. function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
  5. function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
  6. function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  7. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  8. function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
  9. function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
  10. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
  11. function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
  12. function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
  13. function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  14. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  15. 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, _toPropertyKey(descriptor.key), descriptor); } }
  16. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  17. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
  18. function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  19. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
  20. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  21. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  22. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
  23. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  24. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  25. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  26. import React, { PureComponent, cloneElement, Children } from 'react';
  27. import PropTypes from 'prop-types';
  28. import { deepEqual } from 'fast-equals';
  29. import createAnimateManager from './AnimateManager';
  30. import { configEasing } from './easing';
  31. import configUpdate from './configUpdate';
  32. import { getTransitionVal, identity } from './util';
  33. var Animate = /*#__PURE__*/function (_PureComponent) {
  34. _inherits(Animate, _PureComponent);
  35. var _super = _createSuper(Animate);
  36. function Animate(props, context) {
  37. var _this;
  38. _classCallCheck(this, Animate);
  39. _this = _super.call(this, props, context);
  40. var _this$props = _this.props,
  41. isActive = _this$props.isActive,
  42. attributeName = _this$props.attributeName,
  43. from = _this$props.from,
  44. to = _this$props.to,
  45. steps = _this$props.steps,
  46. children = _this$props.children,
  47. duration = _this$props.duration;
  48. _this.handleStyleChange = _this.handleStyleChange.bind(_assertThisInitialized(_this));
  49. _this.changeStyle = _this.changeStyle.bind(_assertThisInitialized(_this));
  50. if (!isActive || duration <= 0) {
  51. _this.state = {
  52. style: {}
  53. };
  54. // if children is a function and animation is not active, set style to 'to'
  55. if (typeof children === 'function') {
  56. _this.state = {
  57. style: to
  58. };
  59. }
  60. return _possibleConstructorReturn(_this);
  61. }
  62. if (steps && steps.length) {
  63. _this.state = {
  64. style: steps[0].style
  65. };
  66. } else if (from) {
  67. if (typeof children === 'function') {
  68. _this.state = {
  69. style: from
  70. };
  71. return _possibleConstructorReturn(_this);
  72. }
  73. _this.state = {
  74. style: attributeName ? _defineProperty({}, attributeName, from) : from
  75. };
  76. } else {
  77. _this.state = {
  78. style: {}
  79. };
  80. }
  81. return _this;
  82. }
  83. _createClass(Animate, [{
  84. key: "componentDidMount",
  85. value: function componentDidMount() {
  86. var _this$props2 = this.props,
  87. isActive = _this$props2.isActive,
  88. canBegin = _this$props2.canBegin;
  89. this.mounted = true;
  90. if (!isActive || !canBegin) {
  91. return;
  92. }
  93. this.runAnimation(this.props);
  94. }
  95. }, {
  96. key: "componentDidUpdate",
  97. value: function componentDidUpdate(prevProps) {
  98. var _this$props3 = this.props,
  99. isActive = _this$props3.isActive,
  100. canBegin = _this$props3.canBegin,
  101. attributeName = _this$props3.attributeName,
  102. shouldReAnimate = _this$props3.shouldReAnimate,
  103. to = _this$props3.to,
  104. currentFrom = _this$props3.from;
  105. var style = this.state.style;
  106. if (!canBegin) {
  107. return;
  108. }
  109. if (!isActive) {
  110. var newState = {
  111. style: attributeName ? _defineProperty({}, attributeName, to) : to
  112. };
  113. if (this.state && style) {
  114. if (attributeName && style[attributeName] !== to || !attributeName && style !== to) {
  115. // eslint-disable-next-line react/no-did-update-set-state
  116. this.setState(newState);
  117. }
  118. }
  119. return;
  120. }
  121. if (deepEqual(prevProps.to, to) && prevProps.canBegin && prevProps.isActive) {
  122. return;
  123. }
  124. var isTriggered = !prevProps.canBegin || !prevProps.isActive;
  125. if (this.manager) {
  126. this.manager.stop();
  127. }
  128. if (this.stopJSAnimation) {
  129. this.stopJSAnimation();
  130. }
  131. var from = isTriggered || shouldReAnimate ? currentFrom : prevProps.to;
  132. if (this.state && style) {
  133. var _newState = {
  134. style: attributeName ? _defineProperty({}, attributeName, from) : from
  135. };
  136. if (attributeName && style[attributeName] !== from || !attributeName && style !== from) {
  137. // eslint-disable-next-line react/no-did-update-set-state
  138. this.setState(_newState);
  139. }
  140. }
  141. this.runAnimation(_objectSpread(_objectSpread({}, this.props), {}, {
  142. from: from,
  143. begin: 0
  144. }));
  145. }
  146. }, {
  147. key: "componentWillUnmount",
  148. value: function componentWillUnmount() {
  149. this.mounted = false;
  150. var onAnimationEnd = this.props.onAnimationEnd;
  151. if (this.unSubscribe) {
  152. this.unSubscribe();
  153. }
  154. if (this.manager) {
  155. this.manager.stop();
  156. this.manager = null;
  157. }
  158. if (this.stopJSAnimation) {
  159. this.stopJSAnimation();
  160. }
  161. if (onAnimationEnd) {
  162. onAnimationEnd();
  163. }
  164. }
  165. }, {
  166. key: "handleStyleChange",
  167. value: function handleStyleChange(style) {
  168. this.changeStyle(style);
  169. }
  170. }, {
  171. key: "changeStyle",
  172. value: function changeStyle(style) {
  173. if (this.mounted) {
  174. this.setState({
  175. style: style
  176. });
  177. }
  178. }
  179. }, {
  180. key: "runJSAnimation",
  181. value: function runJSAnimation(props) {
  182. var _this2 = this;
  183. var from = props.from,
  184. to = props.to,
  185. duration = props.duration,
  186. easing = props.easing,
  187. begin = props.begin,
  188. onAnimationEnd = props.onAnimationEnd,
  189. onAnimationStart = props.onAnimationStart;
  190. var startAnimation = configUpdate(from, to, configEasing(easing), duration, this.changeStyle);
  191. var finalStartAnimation = function finalStartAnimation() {
  192. _this2.stopJSAnimation = startAnimation();
  193. };
  194. this.manager.start([onAnimationStart, begin, finalStartAnimation, duration, onAnimationEnd]);
  195. }
  196. }, {
  197. key: "runStepAnimation",
  198. value: function runStepAnimation(props) {
  199. var _this3 = this;
  200. var steps = props.steps,
  201. begin = props.begin,
  202. onAnimationStart = props.onAnimationStart;
  203. var _steps$ = steps[0],
  204. initialStyle = _steps$.style,
  205. _steps$$duration = _steps$.duration,
  206. initialTime = _steps$$duration === void 0 ? 0 : _steps$$duration;
  207. var addStyle = function addStyle(sequence, nextItem, index) {
  208. if (index === 0) {
  209. return sequence;
  210. }
  211. var duration = nextItem.duration,
  212. _nextItem$easing = nextItem.easing,
  213. easing = _nextItem$easing === void 0 ? 'ease' : _nextItem$easing,
  214. style = nextItem.style,
  215. nextProperties = nextItem.properties,
  216. onAnimationEnd = nextItem.onAnimationEnd;
  217. var preItem = index > 0 ? steps[index - 1] : nextItem;
  218. var properties = nextProperties || Object.keys(style);
  219. if (typeof easing === 'function' || easing === 'spring') {
  220. return [].concat(_toConsumableArray(sequence), [_this3.runJSAnimation.bind(_this3, {
  221. from: preItem.style,
  222. to: style,
  223. duration: duration,
  224. easing: easing
  225. }), duration]);
  226. }
  227. var transition = getTransitionVal(properties, duration, easing);
  228. var newStyle = _objectSpread(_objectSpread(_objectSpread({}, preItem.style), style), {}, {
  229. transition: transition
  230. });
  231. return [].concat(_toConsumableArray(sequence), [newStyle, duration, onAnimationEnd]).filter(identity);
  232. };
  233. return this.manager.start([onAnimationStart].concat(_toConsumableArray(steps.reduce(addStyle, [initialStyle, Math.max(initialTime, begin)])), [props.onAnimationEnd]));
  234. }
  235. }, {
  236. key: "runAnimation",
  237. value: function runAnimation(props) {
  238. if (!this.manager) {
  239. this.manager = createAnimateManager();
  240. }
  241. var begin = props.begin,
  242. duration = props.duration,
  243. attributeName = props.attributeName,
  244. propsTo = props.to,
  245. easing = props.easing,
  246. onAnimationStart = props.onAnimationStart,
  247. onAnimationEnd = props.onAnimationEnd,
  248. steps = props.steps,
  249. children = props.children;
  250. var manager = this.manager;
  251. this.unSubscribe = manager.subscribe(this.handleStyleChange);
  252. if (typeof easing === 'function' || typeof children === 'function' || easing === 'spring') {
  253. this.runJSAnimation(props);
  254. return;
  255. }
  256. if (steps.length > 1) {
  257. this.runStepAnimation(props);
  258. return;
  259. }
  260. var to = attributeName ? _defineProperty({}, attributeName, propsTo) : propsTo;
  261. var transition = getTransitionVal(Object.keys(to), duration, easing);
  262. manager.start([onAnimationStart, begin, _objectSpread(_objectSpread({}, to), {}, {
  263. transition: transition
  264. }), duration, onAnimationEnd]);
  265. }
  266. }, {
  267. key: "render",
  268. value: function render() {
  269. var _this$props4 = this.props,
  270. children = _this$props4.children,
  271. begin = _this$props4.begin,
  272. duration = _this$props4.duration,
  273. attributeName = _this$props4.attributeName,
  274. easing = _this$props4.easing,
  275. isActive = _this$props4.isActive,
  276. steps = _this$props4.steps,
  277. from = _this$props4.from,
  278. to = _this$props4.to,
  279. canBegin = _this$props4.canBegin,
  280. onAnimationEnd = _this$props4.onAnimationEnd,
  281. shouldReAnimate = _this$props4.shouldReAnimate,
  282. onAnimationReStart = _this$props4.onAnimationReStart,
  283. others = _objectWithoutProperties(_this$props4, _excluded);
  284. var count = Children.count(children);
  285. // eslint-disable-next-line react/destructuring-assignment
  286. var stateStyle = this.state.style;
  287. if (typeof children === 'function') {
  288. return children(stateStyle);
  289. }
  290. if (!isActive || count === 0 || duration <= 0) {
  291. return children;
  292. }
  293. var cloneContainer = function cloneContainer(container) {
  294. var _container$props = container.props,
  295. _container$props$styl = _container$props.style,
  296. style = _container$props$styl === void 0 ? {} : _container$props$styl,
  297. className = _container$props.className;
  298. var res = /*#__PURE__*/cloneElement(container, _objectSpread(_objectSpread({}, others), {}, {
  299. style: _objectSpread(_objectSpread({}, style), stateStyle),
  300. className: className
  301. }));
  302. return res;
  303. };
  304. if (count === 1) {
  305. return cloneContainer(Children.only(children));
  306. }
  307. return /*#__PURE__*/React.createElement("div", null, Children.map(children, function (child) {
  308. return cloneContainer(child);
  309. }));
  310. }
  311. }]);
  312. return Animate;
  313. }(PureComponent);
  314. Animate.displayName = 'Animate';
  315. Animate.defaultProps = {
  316. begin: 0,
  317. duration: 1000,
  318. from: '',
  319. to: '',
  320. attributeName: '',
  321. easing: 'ease',
  322. isActive: true,
  323. canBegin: true,
  324. steps: [],
  325. onAnimationEnd: function onAnimationEnd() {},
  326. onAnimationStart: function onAnimationStart() {}
  327. };
  328. Animate.propTypes = {
  329. from: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
  330. to: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
  331. attributeName: PropTypes.string,
  332. // animation duration
  333. duration: PropTypes.number,
  334. begin: PropTypes.number,
  335. easing: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
  336. steps: PropTypes.arrayOf(PropTypes.shape({
  337. duration: PropTypes.number.isRequired,
  338. style: PropTypes.object.isRequired,
  339. easing: PropTypes.oneOfType([PropTypes.oneOf(['ease', 'ease-in', 'ease-out', 'ease-in-out', 'linear']), PropTypes.func]),
  340. // transition css properties(dash case), optional
  341. properties: PropTypes.arrayOf('string'),
  342. onAnimationEnd: PropTypes.func
  343. })),
  344. children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
  345. isActive: PropTypes.bool,
  346. canBegin: PropTypes.bool,
  347. onAnimationEnd: PropTypes.func,
  348. // decide if it should reanimate with initial from style when props change
  349. shouldReAnimate: PropTypes.bool,
  350. onAnimationStart: PropTypes.func,
  351. onAnimationReStart: PropTypes.func
  352. };
  353. export default Animate;