-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
119 lines (99 loc) · 2.62 KB
/
index.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
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import {MDCFloatingLabelFoundation} from '@material/floating-label';
export default class FloatingLabel extends React.Component {
foundation_ = null;
constructor(props) {
super(props);
this.labelElement = React.createRef();
}
state = {
classList: new Set(),
};
componentDidMount() {
this.initializeFoundation();
this.handleWidthChange();
if (this.props.float) {
this.foundation_.float(true);
}
}
componentWillUnmount() {
this.foundation_.destroy();
}
componentWillReceiveProps(nextProps) {
if (this.props.float !== nextProps.float) {
this.foundation_.float(nextProps.float);
}
}
componentDidUpdate(prevProps) {
if (this.props.children !== prevProps.children) {
this.handleWidthChange();
}
}
initializeFoundation = () => {
this.foundation_ = new MDCFloatingLabelFoundation(this.adapter);
this.foundation_.init();
}
get classes() {
const {classList} = this.state;
const {className} = this.props;
return classnames('mdc-floating-label', Array.from(classList), className);
}
get adapter() {
return {
addClass: (className) =>
this.setState({classList: this.state.classList.add(className)}),
removeClass: this.removeClassFromClassList,
};
}
// must be called via ref
shake = () => {
this.foundation_.shake(true);
}
removeClassFromClassList = (className) => {
const {classList} = this.state;
classList.delete(className);
this.setState({classList});
}
handleWidthChange = () => {
const {handleWidthChange} = this.props;
if (this.labelElement.current) {
handleWidthChange(this.labelElement.current.offsetWidth);
}
}
onShakeEnd = () => {
const {LABEL_SHAKE} = MDCFloatingLabelFoundation.cssClasses;
this.removeClassFromClassList(LABEL_SHAKE);
}
render() {
const {
className, // eslint-disable-line no-unused-vars
children,
handleWidthChange, // eslint-disable-line no-unused-vars
float, // eslint-disable-line no-unused-vars
...otherProps
} = this.props;
return (
<label
className={this.classes}
ref={this.labelElement}
onAnimationEnd={this.onShakeEnd}
{...otherProps}
>
{children}
</label>
);
}
}
FloatingLabel.propTypes = {
className: PropTypes.string,
children: PropTypes.node,
handleWidthChange: PropTypes.func,
float: PropTypes.bool,
};
FloatingLabel.defaultProps = {
className: '',
handleWidthChange: () => {},
float: false,
};