File size: 2,209 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import clsx from 'clsx';
import { localize, translate } from 'i18n-calypso';
import { omit } from 'lodash';
import PropTypes from 'prop-types';
import { Component } from 'react';
import FormTextarea from 'calypso/components/forms/form-textarea';

import './style.scss';

const noop = () => {};

export class CountedTextarea extends Component {
	static propTypes = {
		value: PropTypes.string,
		placeholder: PropTypes.string,
		countPlaceholderLength: PropTypes.bool,
		onChange: PropTypes.func,
		acceptableLength: PropTypes.number,
		showRemainingCharacters: PropTypes.bool,
		translate: PropTypes.func,
	};

	static defaultProps = {
		value: '',
		placeholder: '',
		countPlaceholderLength: false,
		onChange: noop,
		showRemainingCharacters: false,
		translate,
	};

	renderCountPanel = () => {
		let length = this.props.value.length;
		if ( ! length && this.props.countPlaceholderLength ) {
			length = this.props.placeholder.length;
		}

		let panelText;
		if ( this.props.showRemainingCharacters && this.props.acceptableLength ) {
			panelText = this.props.translate( '%d character remaining', '%d characters remaining', {
				context: 'Input length',
				args: [ this.props.acceptableLength - length ],
				count: this.props.acceptableLength - length,
			} );
		} else {
			panelText = this.props.translate( '%d character', '%d characters', {
				context: 'Input length',
				args: [ length ],
				count: length,
			} );
		}

		return (
			<div className="counted-textarea__count-panel">
				{ panelText }
				{ this.props.children }
			</div>
		);
	};

	render() {
		const classes = clsx( 'counted-textarea', this.props.className, {
			'is-exceeding-acceptable-length':
				this.props.acceptableLength && this.props.value.length > this.props.acceptableLength,
		} );

		return (
			<div className={ classes }>
				<FormTextarea
					{ ...omit(
						this.props,
						'className',
						'acceptableLength',
						'showRemainingCharacters',
						'children',
						'countPlaceholderLength',
						'moment',
						'numberFormat',
						'translate'
					) }
					className="counted-textarea__input"
				/>
				{ this.renderCountPanel() }
			</div>
		);
	}
}

export default localize( CountedTextarea );