/
animate.tsx
89 lines (77 loc) · 2.32 KB
/
animate.tsx
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
import "./animate.scss";
import * as React from "react";
import { observable, reaction } from "mobx";
import { disposeOnUnmount, observer } from "mobx-react";
import { autobind, cssNames, noop } from "../../utils";
export type AnimateName = "opacity" | "slide-right" | "opacity-scale" | string;
export interface AnimateProps {
name?: AnimateName; // predefined names in css
enter?: boolean;
onEnter?: () => void;
onLeave?: () => void;
}
@observer
export class Animate extends React.Component<AnimateProps> {
static VISIBILITY_DELAY_MS = 100;
static defaultProps: AnimateProps = {
name: "opacity",
enter: true,
onEnter: noop,
onLeave: noop,
};
@observable isVisible = !!this.props.enter;
@observable statusClassName = {
enter: false,
leave: false
};
get contentElem() {
return React.Children.only(this.props.children) as React.ReactElement<React.HTMLAttributes<any>>;
}
componentDidMount() {
disposeOnUnmount(this, [
reaction(() => this.props.enter, enter => {
if (enter) this.enter();
else this.leave();
}, {
delay: Animate.VISIBILITY_DELAY_MS,
fireImmediately: true,
})
])
}
enter() {
this.isVisible = true; // triggers render() to apply css-animation in existing dom
requestAnimationFrame(() => {
this.statusClassName.enter = true;
this.props.onEnter();
});
}
leave() {
if (!this.isVisible) return;
this.statusClassName.leave = true;
this.props.onLeave();
}
reset() {
this.isVisible = false;
this.statusClassName.enter = false;
this.statusClassName.leave = false;
}
@autobind()
onTransitionEnd(evt: React.TransitionEvent) {
var { enter, leave } = this.statusClassName;
var { onTransitionEnd } = this.contentElem.props;
if (onTransitionEnd) onTransitionEnd(evt);
// todo: check evt.propertyName and make sure all animating props has finished their transition
if (enter && leave) {
this.reset();
}
}
render() {
var { name } = this.props;
var contentElem = this.contentElem;
return React.cloneElement(contentElem, {
className: cssNames("Animate", name, contentElem.props.className, this.statusClassName),
children: this.isVisible ? contentElem.props.children : null,
onTransitionEnd: this.onTransitionEnd,
});
}
}