UNPKG

2.57 kBJavaScriptView Raw
1import React from 'react';
2import PropTypes from 'prop-types';
3import toCSS from 'style-to-css';
4import uniqueId from 'mini-unique-id';
5
6const PLACEHOLDER_PREFIXES = [
7 '::-webkit-input-placeholder',
8 '::-moz-placeholder',
9 ':-ms-input-placeholder',
10 ':placeholder-shown',
11];
12
13export default class Input extends React.Component {
14 constructor(props) {
15 super(props);
16 this.id = `Input-${uniqueId()}`;
17 }
18
19 render() {
20 const {context, id} = this;
21 const {
22 disabled,
23 onEnter,
24 placeholder,
25 _ref,
26 style,
27 styleDisabled,
28 styleFocus,
29 styleHover,
30 stylePlaceholder,
31 styleWrapper,
32 ...rest
33 } = this.props;
34
35 let finalStyle = style;
36
37 const backgroundColor = (style && style.backgroundColor) || 'transparent';
38 const color = (style && style.color) || 'black';
39 const inlineStyle = [
40 `#${id}:-webkit-autofill {
41 background-color: ${backgroundColor} !important;
42 box-shadow: 0 0 0px 1000px ${backgroundColor} inset;
43 color: ${color} !important;
44 }`,
45 ];
46
47 if (stylePlaceholder) {
48 PLACEHOLDER_PREFIXES.forEach(prefix => {
49 inlineStyle.push(`#${id}${prefix} {${toCSS(stylePlaceholder)}}`);
50 });
51 }
52
53 if (styleDisabled && disabled) {
54 finalStyle = {
55 ...style,
56 ...styleDisabled,
57 };
58 } else {
59 if (styleHover) {
60 inlineStyle.push(`${inlineStyle} #${id}:hover {${toCSS(styleHover)}}`);
61 }
62 if (styleFocus) {
63 inlineStyle.push(`#${id}:focus {${toCSS(styleFocus)}}`);
64 }
65 }
66
67 let onKeyUp;
68 if (typeof onEnter !== 'undefined') {
69 /* eslint-disable no-console */
70 const finalOnEnter =
71 typeof onEnter === 'function' ? onEnter : () => console.log(onEnter);
72 onKeyUp = event => event.key === 'Enter' && finalOnEnter(event);
73 }
74
75 return (
76 <div style={styleWrapper}>
77 <style>{inlineStyle.join('\n')}</style>
78 <input
79 {...rest}
80 autoComplete="off"
81 id={id}
82 onKeyUp={onKeyUp}
83 ref={_ref}
84 placeholder={
85 placeholder ? context.i18n ? (
86 context.i18n.t(placeholder)
87 ) : (
88 placeholder
89 ) : (
90 undefined
91 )
92 }
93 style={finalStyle}
94 />
95 </div>
96 );
97 }
98}
99
100Input.defaultProps = {
101 placeholder: '',
102 style: {},
103 styleHover: {},
104 styleWrapper: {},
105 type: 'text',
106};
107
108Input.contextTypes = {
109 i18n: PropTypes.shape({
110 t: PropTypes.func.isRequired,
111 }),
112};