File size: 2,518 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 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 120 121 122 123 124 125 126 | import { Button } from '@wordpress/components';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import { useState, useCallback } from 'react';
import FormTextInput from 'calypso/components/forms/form-text-input';
import './style.scss';
const noop = () => {};
function FormTextInputWithAction( {
className,
clearOnSubmit = false,
action,
inputRef,
onFocus = noop,
onBlur = noop,
onKeyDown = noop,
onChange = noop,
onAction = noop,
defaultValue = '',
disabled,
isError,
isValid,
...props
} ) {
const [ focused, setFocused ] = useState( false );
const [ value, setValue ] = useState( defaultValue );
const handleFocus = useCallback(
( e ) => {
setFocused( true );
onFocus( e );
},
[ onFocus ]
);
const handleBlur = useCallback(
( e ) => {
setFocused( false );
onBlur( e );
},
[ onBlur ]
);
const handleChange = useCallback(
( e ) => {
setValue( e.target.value );
onChange( e.target.value, e );
},
[ onChange ]
);
const handleAction = useCallback(
( e ) => {
onAction( value, e );
if ( clearOnSubmit ) {
setValue( '' );
}
},
[ clearOnSubmit, onAction, value ]
);
const handleKeyDown = useCallback(
( e ) => {
onKeyDown( e );
if ( e.which === 13 && value ) {
handleAction( e );
}
},
[ handleAction, onKeyDown, value ]
);
return (
<div
className={ clsx( 'form-text-input-with-action', className, {
'is-focused': focused,
'is-disabled': disabled,
'is-error': isError,
'is-valid': isValid,
} ) }
role="group"
>
<FormTextInput
{ ...props }
className="form-text-input-with-action__input"
ref={ inputRef }
disabled={ disabled }
value={ value }
onChange={ handleChange }
onFocus={ handleFocus }
onBlur={ handleBlur }
onKeyDown={ handleKeyDown }
/>
<Button
size="compact"
className="form-text-input-with-action__button"
variant="tertiary"
disabled={ disabled || ! value }
accessibleWhenDisabled
onClick={ handleAction }
>
{ action }
</Button>
</div>
);
}
FormTextInputWithAction.propTypes = {
className: PropTypes.string,
clearOnSubmit: PropTypes.bool,
action: PropTypes.node,
inputRef: PropTypes.func,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
onKeyDown: PropTypes.func,
onChange: PropTypes.func,
onAction: PropTypes.func,
defaultValue: PropTypes.string,
disabled: PropTypes.bool,
isError: PropTypes.bool,
isValid: PropTypes.bool,
};
export default FormTextInputWithAction;
|